diff --git a/.gitignore b/.gitignore
index ae2899e088..6917571df2 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,15 +1,3 @@
-.gitattributes
-
-*.so
-*.o
-*.a
-
-manual/manual.html
-
-testes/time.txt
-testes/time-debug.txt
-
-testes/libs/all
-
-temp
-lua
+*.[oa]
+src/lua
+src/luac
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000000..7fa91c858b
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,114 @@
+# Makefile for installing Lua
+# See doc/readme.html for installation and customization instructions.
+
+# == CHANGE THE SETTINGS BELOW TO SUIT YOUR ENVIRONMENT =======================
+
+# Your platform. See PLATS for possible values.
+PLAT= none
+
+# Where to install. The installation starts in the src and doc directories,
+# so take care if INSTALL_TOP is not an absolute path. See the local target.
+# You may want to make INSTALL_LMOD and INSTALL_CMOD consistent with
+# LUA_ROOT, LUA_LDIR, and LUA_CDIR in luaconf.h.
+INSTALL_TOP= /usr/local
+INSTALL_BIN= $(INSTALL_TOP)/bin
+INSTALL_INC= $(INSTALL_TOP)/include
+INSTALL_LIB= $(INSTALL_TOP)/lib
+INSTALL_MAN= $(INSTALL_TOP)/man/man1
+INSTALL_LMOD= $(INSTALL_TOP)/share/lua/$V
+INSTALL_CMOD= $(INSTALL_TOP)/lib/lua/$V
+
+# How to install. If your install program does not support "-p", then
+# you may have to run ranlib on the installed liblua.a.
+INSTALL= install -p
+INSTALL_EXEC= $(INSTALL) -m 0755
+INSTALL_DATA= $(INSTALL) -m 0644
+#
+# If you don't have "install" you can use "cp" instead.
+# INSTALL= cp -p
+# INSTALL_EXEC= $(INSTALL)
+# INSTALL_DATA= $(INSTALL)
+
+# Other utilities.
+MKDIR= mkdir -p
+RM= rm -f
+
+# == END OF USER SETTINGS -- NO NEED TO CHANGE ANYTHING BELOW THIS LINE =======
+
+# Convenience platforms targets.
+PLATS= aix bsd c89 freebsd generic linux macosx mingw posix solaris
+
+# What to install.
+TO_BIN= lua luac
+TO_INC= lua.h luaconf.h lualib.h lauxlib.h lua.hpp
+TO_LIB= liblua.a
+TO_MAN= lua.1 luac.1
+
+# Lua version and release.
+V= 5.3
+R= $V.0
+
+# Targets start here.
+all: $(PLAT)
+
+$(PLATS) clean:
+ cd src && $(MAKE) $@
+
+test: dummy
+ src/lua -v
+
+install: dummy
+ cd src && $(MKDIR) $(INSTALL_BIN) $(INSTALL_INC) $(INSTALL_LIB) $(INSTALL_MAN) $(INSTALL_LMOD) $(INSTALL_CMOD)
+ cd src && $(INSTALL_EXEC) $(TO_BIN) $(INSTALL_BIN)
+ cd src && $(INSTALL_DATA) $(TO_INC) $(INSTALL_INC)
+ cd src && $(INSTALL_DATA) $(TO_LIB) $(INSTALL_LIB)
+ cd doc && $(INSTALL_DATA) $(TO_MAN) $(INSTALL_MAN)
+
+uninstall:
+ cd src && cd $(INSTALL_BIN) && $(RM) $(TO_BIN)
+ cd src && cd $(INSTALL_INC) && $(RM) $(TO_INC)
+ cd src && cd $(INSTALL_LIB) && $(RM) $(TO_LIB)
+ cd doc && cd $(INSTALL_MAN) && $(RM) $(TO_MAN)
+
+local:
+ $(MAKE) install INSTALL_TOP=../install
+
+none:
+ @echo "Please do 'make PLATFORM' where PLATFORM is one of these:"
+ @echo " $(PLATS)"
+ @echo "See doc/readme.html for complete instructions."
+
+# make may get confused with test/ and install/
+dummy:
+
+# echo config parameters
+echo:
+ @cd src && $(MAKE) -s echo
+ @echo "PLAT= $(PLAT)"
+ @echo "V= $V"
+ @echo "R= $R"
+ @echo "TO_BIN= $(TO_BIN)"
+ @echo "TO_INC= $(TO_INC)"
+ @echo "TO_LIB= $(TO_LIB)"
+ @echo "TO_MAN= $(TO_MAN)"
+ @echo "INSTALL_TOP= $(INSTALL_TOP)"
+ @echo "INSTALL_BIN= $(INSTALL_BIN)"
+ @echo "INSTALL_INC= $(INSTALL_INC)"
+ @echo "INSTALL_LIB= $(INSTALL_LIB)"
+ @echo "INSTALL_MAN= $(INSTALL_MAN)"
+ @echo "INSTALL_LMOD= $(INSTALL_LMOD)"
+ @echo "INSTALL_CMOD= $(INSTALL_CMOD)"
+ @echo "INSTALL_EXEC= $(INSTALL_EXEC)"
+ @echo "INSTALL_DATA= $(INSTALL_DATA)"
+
+# echo pkg-config data
+pc:
+ @echo "version=$R"
+ @echo "prefix=$(INSTALL_TOP)"
+ @echo "libdir=$(INSTALL_LIB)"
+ @echo "includedir=$(INSTALL_INC)"
+
+# list targets that do not create files (but not all makes understand .PHONY)
+.PHONY: all $(PLATS) clean test install local none dummy echo pecho lecho
+
+# (end of Makefile)
diff --git a/README b/README
new file mode 100644
index 0000000000..32fb68e77e
--- /dev/null
+++ b/README
@@ -0,0 +1,6 @@
+
+This is Lua 5.3.0, released on 06 Jan 2015.
+
+For installation instructions, license details, and
+further information about Lua, see doc/readme.html.
+
diff --git a/README.md b/README.md
deleted file mode 100644
index 5bc0ee77c4..0000000000
--- a/README.md
+++ /dev/null
@@ -1,7 +0,0 @@
-# Lua
-
-This is the repository of Lua development code, as seen by the Lua team. It contains the full history of all commits but is mirrored irregularly. For complete information about Lua, visit [Lua.org](https://www.lua.org/).
-
-Please **do not** send pull requests. To report issues, post a message to the [Lua mailing list](https://www.lua.org/lua-l.html).
-
-Download official Lua releases from [Lua.org](https://www.lua.org/download.html).
diff --git a/all b/all
deleted file mode 100755
index 86f38ac1c3..0000000000
--- a/all
+++ /dev/null
@@ -1,9 +0,0 @@
-make -s -j
-cd testes/libs; make -s
-cd .. # back to directory 'testes'
-ulimit -S -s 1100
-if { ../lua -W all.lua; } then
- echo -e "\n\n final OK!!!!\n\n"
-else
- echo -e "\n\n >>>> BUG!!!!\n\n"
-fi
diff --git a/doc/contents.html b/doc/contents.html
new file mode 100644
index 0000000000..e59e4215ee
--- /dev/null
+++ b/doc/contents.html
@@ -0,0 +1,619 @@
+
+
+
+The reference manual is the official definition of the Lua language.
+For a complete introduction to Lua programming, see the book
+Programming in Lua.
+
+
+
+
+
+Last update:
+Tue Dec 9 21:26:07 BRST 2014
+
+
+
+
+
diff --git a/doc/logo.gif b/doc/logo.gif
new file mode 100644
index 0000000000..2f5e4ac2e7
Binary files /dev/null and b/doc/logo.gif differ
diff --git a/doc/lua.1 b/doc/lua.1
new file mode 100644
index 0000000000..411531b9ed
--- /dev/null
+++ b/doc/lua.1
@@ -0,0 +1,111 @@
+.TH LUA 1 "$Date: 2014/12/10 15:55:45 $"
+.SH NAME
+lua \- Lua interpreter
+.SH SYNOPSIS
+.B lua
+[
+.I options
+]
+[
+.I script
+[
+.I args
+]
+]
+.SH DESCRIPTION
+.B lua
+is the standalone Lua interpreter.
+It loads and executes Lua programs,
+either in textual source form or
+in precompiled binary form.
+(Precompiled binaries are output by
+.BR luac ,
+the Lua compiler.)
+.B lua
+can be used as a batch interpreter and also interactively.
+.LP
+The given
+.I options
+are handled in order and then
+the Lua program in file
+.I script
+is loaded and executed.
+The given
+.I args
+are available to
+.I script
+as strings in a global table named
+.BR arg .
+If no options or arguments are given,
+then
+.B "\-v \-i"
+is assumed when the standard input is a terminal;
+otherwise,
+.B "\-"
+is assumed.
+.LP
+In interactive mode,
+.B lua
+prompts the user,
+reads lines from the standard input,
+and executes them as they are read.
+If the line contains an expression or list of expressions,
+then the line is evaluated and the results are printed.
+If a line does not contain a complete statement,
+then a secondary prompt is displayed and
+lines are read until a complete statement is formed or
+a syntax error is found.
+.LP
+At the very start,
+before even handling the command line,
+.B lua
+checks the contents of the environment variables
+.B LUA_INIT_5_3
+or
+.BR LUA_INIT ,
+in that order.
+If the contents is of the form
+.RI '@ filename ',
+then
+.I filename
+is executed.
+Otherwise, the string is assumed to be a Lua statement and is executed.
+.SH OPTIONS
+.TP
+.BI \-e " stat"
+execute statement
+.IR stat .
+.TP
+.B \-i
+enter interactive mode after executing
+.IR script .
+.TP
+.BI \-l " name"
+execute the equivalent of
+.IB name =require(' name ')
+before executing
+.IR script .
+.TP
+.B \-v
+show version information.
+.TP
+.B \-E
+ignore environment variables.
+.TP
+.B \-\-
+stop handling options.
+.TP
+.B \-
+stop handling options and execute the standard input as a file.
+.SH "SEE ALSO"
+.BR luac (1)
+.br
+The documentation at lua.org,
+especially section 7 of the reference manual.
+.SH DIAGNOSTICS
+Error messages should be self explanatory.
+.SH AUTHORS
+R. Ierusalimschy,
+L. H. de Figueiredo,
+W. Celes
+.\" EOF
diff --git a/doc/lua.css b/doc/lua.css
new file mode 100644
index 0000000000..3199a2b6e8
--- /dev/null
+++ b/doc/lua.css
@@ -0,0 +1,105 @@
+html {
+ background-color: #F8F8F8 ;
+}
+
+body {
+ border: solid #a0a0a0 1px ;
+ border-radius: 20px ;
+ padding: 26px ;
+ margin: 16px ;
+ color: #000000 ;
+ background-color: #FFFFFF ;
+ font-family: Helvetica, Arial, sans-serif ;
+ text-align: justify ;
+}
+
+h1, h2, h3, h4 {
+ font-family: Verdana, Geneva, sans-serif ;
+ font-weight: normal ;
+ font-style: normal ;
+}
+
+h2 {
+ padding-top: 0.4em ;
+ padding-bottom: 0.4em ;
+ padding-left: 0.8em ;
+ padding-right: 0.8em ;
+ background-color: #D0D0FF ;
+ border-radius: 8px ;
+ border: solid #a0a0a0 1px ;
+}
+
+h3 {
+ padding-left: 0.5em ;
+ border-left: solid #D0D0FF 1em ;
+}
+
+table h3 {
+ padding-left: 0px ;
+ border-left: none ;
+}
+
+a:link {
+ color: #000080 ;
+ background-color: inherit ;
+ text-decoration: none ;
+}
+
+a:visited {
+ background-color: inherit ;
+ text-decoration: none ;
+}
+
+a:link:hover, a:visited:hover {
+ color: #000080 ;
+ background-color: #D0D0FF ;
+ border-radius: 4px;
+}
+
+a:link:active, a:visited:active {
+ color: #FF0000 ;
+}
+
+h1 a img {
+ vertical-align: text-bottom ;
+}
+
+hr {
+ border: 0 ;
+ height: 1px ;
+ color: #a0a0a0 ;
+ background-color: #a0a0a0 ;
+ display: none ;
+}
+
+table hr {
+ display: block ;
+}
+
+:target {
+ background-color: #F8F8F8 ;
+ padding: 8px ;
+ border: solid #a0a0a0 2px ;
+ border-radius: 8px ;
+}
+
+.footer {
+ color: gray ;
+ font-size: x-small ;
+}
+
+input[type=text] {
+ border: solid #a0a0a0 2px ;
+ border-radius: 2em ;
+ background-image: url('images/search.png') ;
+ background-repeat: no-repeat ;
+ background-position: 4px center ;
+ padding-left: 20px ;
+ height: 2em ;
+}
+
+pre.session {
+ background-color: #F8F8F8 ;
+ padding: 1em ;
+ border-radius: 8px ;
+}
diff --git a/doc/luac.1 b/doc/luac.1
new file mode 100644
index 0000000000..33a4ed00ac
--- /dev/null
+++ b/doc/luac.1
@@ -0,0 +1,118 @@
+.\" $Id: luac.man,v 1.29 2011/11/16 13:53:40 lhf Exp $
+.TH LUAC 1 "$Date: 2011/11/16 13:53:40 $"
+.SH NAME
+luac \- Lua compiler
+.SH SYNOPSIS
+.B luac
+[
+.I options
+] [
+.I filenames
+]
+.SH DESCRIPTION
+.B luac
+is the Lua compiler.
+It translates programs written in the Lua programming language
+into binary files containing precompiled chunks
+that can be later loaded and executed.
+.LP
+The main advantages of precompiling chunks are:
+faster loading,
+protecting source code from accidental user changes,
+and
+off-line syntax checking.
+Precompiling does not imply faster execution
+because in Lua chunks are always compiled into bytecodes before being executed.
+.B luac
+simply allows those bytecodes to be saved in a file for later execution.
+Precompiled chunks are not necessarily smaller than the corresponding source.
+The main goal in precompiling is faster loading.
+.LP
+In the command line,
+you can mix
+text files containing Lua source and
+binary files containing precompiled chunks.
+.B luac
+produces a single output file containing the combined bytecodes
+for all files given.
+Executing the combined file is equivalent to executing the given files.
+By default,
+the output file is named
+.BR luac.out ,
+but you can change this with the
+.B \-o
+option.
+.LP
+Precompiled chunks are
+.I not
+portable across different architectures.
+Moreover,
+the internal format of precompiled chunks
+is likely to change when a new version of Lua is released.
+Make sure you save the source files of all Lua programs that you precompile.
+.LP
+.SH OPTIONS
+.TP
+.B \-l
+produce a listing of the compiled bytecode for Lua's virtual machine.
+Listing bytecodes is useful to learn about Lua's virtual machine.
+If no files are given, then
+.B luac
+loads
+.B luac.out
+and lists its contents.
+Use
+.B \-l \-l
+for a full listing.
+.TP
+.BI \-o " file"
+output to
+.IR file ,
+instead of the default
+.BR luac.out .
+(You can use
+.B "'\-'"
+for standard output,
+but not on platforms that open standard output in text mode.)
+The output file may be one of the given files because
+all files are loaded before the output file is written.
+Be careful not to overwrite precious files.
+.TP
+.B \-p
+load files but do not generate any output file.
+Used mainly for syntax checking and for testing precompiled chunks:
+corrupted files will probably generate errors when loaded.
+If no files are given, then
+.B luac
+loads
+.B luac.out
+and tests its contents.
+No messages are displayed if the file loads without errors.
+.TP
+.B \-s
+strip debug information before writing the output file.
+This saves some space in very large chunks,
+but if errors occur when running a stripped chunk,
+then the error messages may not contain the full information they usually do.
+In particular,
+line numbers and names of local variables are lost.
+.TP
+.B \-v
+show version information.
+.TP
+.B \-\-
+stop handling options.
+.TP
+.B \-
+stop handling options and process standard input.
+.SH "SEE ALSO"
+.BR lua (1)
+.br
+The documentation at lua.org.
+.SH DIAGNOSTICS
+Error messages should be self explanatory.
+.SH AUTHORS
+R. Ierusalimschy,
+L. H. de Figueiredo,
+W. Celes
+.\" EOF
diff --git a/doc/manual.css b/doc/manual.css
new file mode 100644
index 0000000000..ca613cd9fb
--- /dev/null
+++ b/doc/manual.css
@@ -0,0 +1,27 @@
+h3 code {
+ font-family: inherit ;
+ font-size: inherit ;
+}
+
+pre, code {
+ font-size: 12pt ;
+}
+
+span.apii {
+ float: right ;
+ font-family: inherit ;
+ font-style: normal ;
+ font-size: small ;
+ color: gray ;
+}
+
+p+h1, ul+h1 {
+ font-style: normal ;
+ padding-top: 0.4em ;
+ padding-bottom: 0.4em ;
+ padding-left: 16px ;
+ margin-left: -16px ;
+ background-color: #D0D0FF ;
+ border-radius: 8px ;
+ border: solid #000080 1px ;
+}
diff --git a/doc/manual.html b/doc/manual.html
new file mode 100644
index 0000000000..5ed8f06922
--- /dev/null
+++ b/doc/manual.html
@@ -0,0 +1,10789 @@
+
+
+
+
+Lua 5.3 Reference Manual
+
+
+
+
+
+
+
+
+
+Lua is an extension programming language designed to support
+general procedural programming with data description
+facilities.
+Lua also offers good support for object-oriented programming,
+functional programming, and data-driven programming.
+Lua is intended to be used as a powerful, lightweight,
+embeddable scripting language for any program that needs one.
+Lua is implemented as a library, written in clean C,
+the common subset of Standard C and C++.
+
+
+
+As an extension language, Lua has no notion of a "main" program:
+it only works embedded in a host client,
+called the embedding program or simply the host.
+The 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.
+The Lua distribution includes a sample host program called lua,
+which uses the Lua library to offer a complete, standalone Lua interpreter,
+for interactive or batch use.
+
+
+
+Lua is free software,
+and is provided as usual with no guarantees,
+as stated in its license.
+The implementation described in this manual is available
+at Lua's official web site, www.lua.org.
+
+
+
+Like any other reference manual,
+this document is dry in places.
+For a discussion of the decisions behind the design of Lua,
+see the technical papers available at Lua's web site.
+For a detailed introduction to programming in Lua,
+see Roberto's book, Programming in Lua.
+
+
+
+
+Lua is a dynamically typed language.
+This means that
+variables do not have types; only values do.
+There are no type definitions in the language.
+All values carry their own type.
+
+
+
+All values in Lua are first-class values.
+This means that all values can be stored in variables,
+passed as arguments to other functions, and returned as results.
+
+
+
+There are eight basic types in Lua:
+nil, boolean, number,
+string, function, userdata,
+thread, and table.
+Nil is the type of the value nil,
+whose main property is to be different from any other value;
+it usually represents the absence of a useful value.
+Boolean is the type of the values false and true.
+Both nil and false make a condition false;
+any other value makes it true.
+Number represents both
+integer numbers and real (floating-point) numbers.
+String represents immutable sequences of bytes.
+
+Lua is 8-bit clean:
+strings can contain any 8-bit value,
+including embedded zeros ('\0').
+Lua is also encoding-agnostic;
+it makes no assumptions about the contents of a string.
+
+
+
+The type number uses two internal representations,
+one called integer and the other called float.
+Lua has explicit rules about when each representation is used,
+but it also converts between them automatically as needed (see §3.4.3).
+Therefore,
+the programmer may choose to mostly ignore the difference
+between integers and floats
+or to assume complete control over the representation of each number.
+Standard Lua uses 64-bit integers and double-precision (64-bit) floats,
+but you can also compile Lua so that it
+uses 32-bit integers and/or single-precision (32-bit) floats.
+The option with 32 bits for both integers and floats
+is particularly attractive
+for small machines and embedded systems.
+(See macro LUA_32BITS in file luaconf.h.)
+
+
+
+Lua can call (and manipulate) functions written in Lua and
+functions written in C (see §3.4.10).
+Both are represented by the type function.
+
+
+
+The type userdata is provided to allow arbitrary C data to
+be stored in Lua variables.
+A userdata value represents a block of raw memory.
+There are two kinds of userdata:
+full userdata,
+which is an object with a block of memory managed by Lua,
+and light userdata,
+which is simply a C pointer value.
+Userdata has no predefined operations in Lua,
+except assignment and identity test.
+By using metatables,
+the programmer can define operations for full userdata values
+(see §2.4).
+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.
+
+
+
+The type thread represents independent threads of execution
+and it is used to implement coroutines (see §2.6).
+Lua threads are not related to operating-system threads.
+Lua supports coroutines on all systems,
+even those that do not support threads natively.
+
+
+
+The type table implements associative arrays,
+that is, arrays that can be indexed not only with numbers,
+but with any Lua value except nil and NaN.
+(Not a Number is a special numeric value used to represent
+undefined or unrepresentable results, such as 0/0.)
+Tables can be heterogeneous;
+that is, they can contain values of all types (except nil).
+Any key with value nil is not considered part of the table.
+Conversely, any key that is not part of a table has
+an associated value nil.
+
+
+
+Tables are the sole data-structuring mechanism in Lua;
+they can be used to represent ordinary arrays, sequences,
+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 a.name as syntactic sugar for a["name"].
+There are several convenient ways to create tables in Lua
+(see §3.4.9).
+
+
+
+We use the term sequence to denote a table where
+the set of all positive numeric keys is equal to {1..n}
+for some non-negative integer n,
+which is called the length of the sequence (see §3.4.7).
+
+
+
+Like indices,
+the values of table fields can be of any type.
+In particular,
+because functions are first-class values,
+table fields can contain functions.
+Thus tables can also carry methods (see §3.4.11).
+
+
+
+The indexing of tables follows
+the definition of raw equality in the language.
+The expressions a[i] and a[j]
+denote the same table element
+if and only if i and j are raw equal
+(that is, equal without metamethods).
+In particular, floats with integral values
+are equal to their respective integers
+(e.g., 1.0 == 1).
+To avoid ambiguities,
+any float with integral value used as a key
+is converted to its respective integer.
+For instance, if you write a[2.0] = true,
+the actual key inserted into the table will be the
+integer 2.
+(On the other hand,
+2 and "2" are different Lua values and therefore
+denote different table entries.)
+
+
+
+Tables, functions, threads, and (full) userdata values are objects:
+variables do not actually contain these values,
+only references to them.
+Assignment, parameter passing, and function returns
+always manipulate references to such values;
+these operations do not imply any kind of copy.
+
+
+
+The library function type returns a string describing the type
+of a given value (see §6.1).
+
+
+
+
+
+
+As will be discussed in §3.2 and §3.3.3,
+any reference to a free name
+(that is, a name not bound to any declaration) var
+is syntactically translated to _ENV.var.
+Moreover, every chunk is compiled in the scope of
+an external local variable named _ENV (see §3.3.2),
+so _ENV itself is never a free name in a chunk.
+
+
+
+Despite the existence of this external _ENV variable and
+the translation of free names,
+_ENV is a completely regular name.
+In particular,
+you can define new variables and parameters with that name.
+Each reference to a free name uses the _ENV that is
+visible at that point in the program,
+following the usual visibility rules of Lua (see §3.5).
+
+
+
+Any table used as the value of _ENV is called an environment.
+
+
+
+Lua keeps a distinguished environment called the global environment.
+This value is kept at a special index in the C registry (see §4.5).
+In Lua, the global variable _G is initialized with this same value.
+(_G is never used internally.)
+
+
+
+When Lua loads a chunk,
+the default value for its _ENV upvalue
+is the global environment (see load).
+Therefore, by default,
+free names in Lua code refer to entries in the global environment
+(and, therefore, they are also called global variables).
+Moreover, all standard libraries are loaded in the global environment
+and some functions there operate on that environment.
+You can use load (or loadfile)
+to load a chunk with a different environment.
+(In C, you have to load the chunk and then change the value
+of its first upvalue.)
+
+
+
+
+
+
+Because Lua is an embedded extension language,
+all Lua actions start from C code in the host program
+calling a function from the Lua library.
+(When you use Lua standalone,
+the lua application is the host program.)
+Whenever an error occurs during
+the compilation or execution of a Lua chunk,
+control returns to the host,
+which can take appropriate measures
+(such as printing an error message).
+
+
+
+Lua code can explicitly generate an error by calling the
+error function.
+If you need to catch errors in Lua,
+you can use pcall or xpcall
+to call a given function in protected mode.
+
+
+
+Whenever there is an error,
+an error object (also called an error message)
+is propagated with information about the error.
+Lua itself only generates errors whose error object is a string,
+but programs may generate errors with
+any value as the error object.
+It is up to the Lua program or its host to handle such error objects.
+
+
+
+When you use xpcall or lua_pcall,
+you may give a message handler
+to be called in case of errors.
+This function is called with the original error message
+and returns a new error message.
+It is called before the error unwinds the stack,
+so that it can gather more information about the error,
+for instance by inspecting the stack and creating a stack traceback.
+This message handler is still protected by the protected call;
+so, an error inside the message handler
+will call the message handler again.
+If this loop goes on for too long,
+Lua breaks it and returns an appropriate message.
+
+
+
+
+
+
+Every value in Lua can have a metatable.
+This metatable 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 "__add" of the value's metatable.
+If it finds one,
+Lua calls this function to perform the addition.
+
+
+
+The keys in a metatable are derived from the event names;
+the corresponding values are called metamethods.
+In the previous example, the event is "add"
+and the metamethod is the function that performs the addition.
+
+
+
+You can query the metatable of any value
+using the getmetatable function.
+
+
+
+You can replace the metatable of tables
+using the setmetatable function.
+You cannot change the metatable of other types from Lua
+(except by using the debug library (§6.10));
+you must use the C API for that.
+
+
+
+Tables and full userdata have individual metatables
+(although multiple tables and userdata can share their metatables).
+Values of all other types share one single metatable per type;
+that is, there is one single metatable for all numbers,
+one for all strings, etc.
+By default, a value has no metatable,
+but the string library sets a metatable for the string type (see §6.4).
+
+
+
+A metatable controls how an object behaves in
+arithmetic operations, bitwise operations,
+order comparisons, concatenation, length operation, calls, and indexing.
+A metatable also can define a function to be called
+when a userdata or a table is garbage collected (§2.5).
+
+
+
+A detailed list of events controlled by metatables is given next.
+Each operation is identified by its corresponding event name.
+The key for each event is a string with its name prefixed by
+two underscores, '__';
+for instance, the key for operation "add" is the
+string "__add".
+Note that queries for metamethods are always raw;
+the access to a metamethod does not invoke other metamethods.
+You can emulate how Lua queries a metamethod for an object obj
+with the following code:
+
+
+ rawget(getmetatable(obj) or {}, "__" .. event_name)
+
+
+
+For the unary operators (negation, length, and bitwise not),
+the metamethod is computed and called with a dummy second operand,
+equal to the first one.
+This extra operand is only to simplify Lua's internals
+(by making these operators behave like a binary operation)
+and may be removed in future versions.
+(For most uses this extra operand is irrelevant.)
+
+
+
+
+
+
"add":
+the + operation.
+
+If any operand for an addition is not a number
+(nor a string coercible to a number),
+Lua will try to call a metamethod.
+First, Lua will check the first operand (even if it is valid).
+If that operand does not define a metamethod for the "__add" event,
+then Lua will check the second operand.
+If Lua can find a metamethod,
+it calls the metamethod with the two operands as arguments,
+and the result of the call
+(adjusted to one value)
+is the result of the operation.
+Otherwise,
+it raises an error.
+
+
+
"sub":
+the - operation.
+
+Behavior similar to the "add" operation.
+
+
+
"mul":
+the * operation.
+
+Behavior similar to the "add" operation.
+
+
+
"div":
+the / operation.
+
+Behavior similar to the "add" operation.
+
+
+
"mod":
+the % operation.
+
+Behavior similar to the "add" operation.
+
+
+
"pow":
+the ^ (exponentiation) operation.
+
+Behavior similar to the "add" operation.
+
+
+
"unm":
+the - (unary minus) operation.
+
+Behavior similar to the "add" operation.
+
+
+
"idiv":
+the // (floor division) operation.
+
+Behavior similar to the "add" operation.
+
+
+
"band":
+the & (bitwise and) operation.
+
+Behavior similar to the "add" operation,
+except that Lua will try a metamethod
+if any operator is neither an integer
+nor a value coercible to an integer (see §3.4.3).
+
+
+
"bor":
+the | (bitwise or) operation.
+
+Behavior similar to the "band" operation.
+
+
+
"bxor":
+the ~ (bitwise exclusive or) operation.
+
+Behavior similar to the "band" operation.
+
+
+
"bnot":
+the ~ (bitwise unary not) operation.
+
+Behavior similar to the "band" operation.
+
+
+
"shl":
+the << (bitwise left shift) operation.
+
+Behavior similar to the "band" operation.
+
+
+
"shr":
+the >> (bitwise right shift) operation.
+
+Behavior similar to the "band" operation.
+
+
+
"concat":
+the .. (concatenation) operation.
+
+Behavior similar to the "add" operation,
+except that Lua will try a metamethod
+if any operator is neither a string nor a number
+(which is always coercible to a string).
+
+
+
"len":
+the # (length) operation.
+
+If the object is not a string,
+Lua will try its metamethod.
+If there is a metamethod,
+Lua calls it with the object as argument,
+and the result of the call
+(always adjusted to one value)
+is the result of the operation.
+If there is no metamethod but the object is a table,
+then Lua uses the table length operation (see §3.4.7).
+Otherwise, Lua raises an error.
+
+
+
"eq":
+the == (equal) operation.
+
+Behavior similar to the "add" operation,
+except that Lua will try a metamethod only when the values
+being compared are either both tables or both full userdata
+and they are not primitively equal.
+The result of the call is always converted to a boolean.
+
+
+
"lt":
+the < (less than) operation.
+
+Behavior similar to the "add" operation,
+except that Lua will try a metamethod only when the values
+being compared are neither both numbers nor both strings.
+The result of the call is always converted to a boolean.
+
+
+
"le":
+the <= (less equal) operation.
+
+Unlike other operations,
+The less-equal operation can use two different events.
+First, Lua looks for the "__le" metamethod in both operands,
+like in the "lt" operation.
+If it cannot find such a metamethod,
+then it will try the "__lt" event,
+assuming that a <= b is equivalent to not (b < a).
+As with the other comparison operators,
+the result is always a boolean.
+
+
+
"index":
+The indexing access table[key].
+
+This event happens when table is not a table or
+when key is not present in table.
+The metamethod is looked up in table.
+
+
+
+Despite the name,
+the metamethod for this event can be either a function or a table.
+If it is a function,
+it is called with table and key as arguments.
+If it is a table,
+the final result is the result of indexing this table with key.
+(This indexing is regular, not raw,
+and therefore can trigger another metamethod.)
+
+
+
"newindex":
+The indexing assignment table[key] = value.
+
+Like the index event,
+this event happens when table is not a table or
+when key is not present in table.
+The metamethod is looked up in table.
+
+
+
+Like with indexing,
+the metamethod for this event can be either a function or a table.
+If it is a function,
+it is called with table, key, and value as arguments.
+If it is a table,
+Lua does an indexing assignment to this table with the same key and value.
+(This assignment is regular, not raw,
+and therefore can trigger another metamethod.)
+
+
+
+Whenever there is a "newindex" metamethod,
+Lua does not perform the primitive assignment.
+(If necessary,
+the metamethod itself can call rawset
+to do the assignment.)
+
+
+
"call":
+The call operation func(args).
+
+This event happens when Lua tries to call a non-function value
+(that is, func is not a function).
+The metamethod is looked up in func.
+If present,
+the metamethod is called with func as its first argument,
+followed by the arguments of the original call (args).
+
+Lua performs automatic memory management.
+This means that
+you do not have to worry about allocating memory for new objects
+or freeing it when the objects are no longer needed.
+Lua manages memory automatically by running
+a garbage collector to collect all dead objects
+(that is, objects that are no longer accessible from Lua).
+All memory used by Lua is subject to automatic management:
+strings, tables, userdata, functions, threads, internal structures, etc.
+
+
+
+Lua implements an incremental mark-and-sweep collector.
+It uses two numbers to control its garbage-collection cycles:
+the garbage-collector pause and
+the garbage-collector step multiplier.
+Both use percentage points as units
+(e.g., a value of 100 means an internal value of 1).
+
+
+
+The garbage-collector pause
+controls how long the collector waits before starting a new cycle.
+Larger values make the collector less aggressive.
+Values smaller than 100 mean the collector will not wait to
+start a new cycle.
+A value of 200 means that the collector waits for the total memory in use
+to double before starting a new cycle.
+
+
+
+The garbage-collector step multiplier
+controls the relative speed of the collector relative to
+memory allocation.
+Larger values make the collector more aggressive but also increase
+the size of each incremental step.
+You should not use values smaller than 100,
+because they make the collector too slow and
+can result in the collector never finishing a cycle.
+The default is 200,
+which means that the collector runs at "twice"
+the speed of memory allocation.
+
+
+
+If you set the step multiplier to a very large number
+(larger than 10% of the maximum number of
+bytes that the program may use),
+the collector behaves like a stop-the-world collector.
+If you then set the pause to 200,
+the collector behaves as in old Lua versions,
+doing a complete collection every time Lua doubles its
+memory usage.
+
+
+
+You can change these numbers by calling lua_gc in C
+or collectgarbage in Lua.
+You can also use these functions to control
+the collector directly (e.g., stop and restart it).
+
+
+
+
+You can set garbage-collector metamethods for tables
+and, using the C API,
+for full userdata (see §2.4).
+These metamethods are also called finalizers.
+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).
+
+
+
+For an object (table or userdata) to be finalized when collected,
+you must mark it for finalization.
+
+You mark an object for finalization when you set its metatable
+and the metatable has a field indexed by the string "__gc".
+Note that if you set a metatable without a __gc field
+and later create that field in the metatable,
+the object will not be marked for finalization.
+However, after an object has been marked,
+you can freely change the __gc field of its metatable.
+
+
+
+When a marked object becomes garbage,
+it is not collected immediately by the garbage collector.
+Instead, Lua puts it in a list.
+After the collection,
+Lua goes through that list.
+For each object in the list,
+it checks the object's __gc metamethod:
+If it is a function,
+Lua calls it with the object as its single argument;
+if the metamethod is not a function,
+Lua simply ignores it.
+
+
+
+At the end of each garbage-collection cycle,
+the finalizers for objects are called in
+the reverse order that the objects were marked for finalization,
+among those collected in that cycle;
+that is, the first finalizer to be called is the one associated
+with the object marked last in the program.
+The execution of each finalizer may occur at any point during
+the execution of the regular code.
+
+
+
+Because the object being collected must still be used by the finalizer,
+that object (and other objects accessible only through it)
+must be resurrected by Lua.
+Usually, this resurrection is transient,
+and the object memory is freed in the next garbage-collection cycle.
+However, if the finalizer stores the object in some global place
+(e.g., a global variable),
+then the resurrection is permanent.
+Moreover, if the finalizer marks a finalizing object for finalization again,
+its finalizer will be called again in the next cycle where the
+object is unreachable.
+In any case,
+the object memory is freed only in the GC cycle where
+the object is unreachable and not marked for finalization.
+
+
+
+When you close a state (see lua_close),
+Lua calls the finalizers of all objects marked for finalization,
+following the reverse order that they were marked.
+If any finalizer marks objects for collection during that phase,
+these marks have no effect.
+
+
+
+
+
+
+A weak table is a table whose elements are
+weak references.
+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.
+
+
+
+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
+__mode field of its metatable.
+If the __mode field is a string containing the character 'k',
+the keys in the table are weak.
+If __mode contains 'v',
+the values in the table are weak.
+
+
+
+A table with weak keys and strong values
+is also called an ephemeron table.
+In an ephemeron table,
+a value is considered reachable only if its key is reachable.
+In particular,
+if the only reference to a key comes through its value,
+the pair is removed.
+
+
+
+Any change in the weakness of a table may take effect only
+at the next collect cycle.
+In particular, if you change the weakness to a stronger mode,
+Lua may still collect some items from that table
+before the change takes effect.
+
+
+
+Only objects that have an explicit construction
+are removed from weak tables.
+Values, such as numbers and light C functions,
+are not subject to garbage collection,
+and therefore are not removed from weak tables
+(unless their associated values are collected).
+Although strings are subject to garbage collection,
+they do not have an explicit construction,
+and therefore are not removed from weak tables.
+
+
+
+Resurrected objects
+(that is, objects being finalized
+and objects accessible only through objects being finalized)
+have a special behavior in weak tables.
+They are removed from weak values before running their finalizers,
+but are removed from weak keys only in the next collection
+after running their finalizers, when such objects are actually freed.
+This behavior allows the finalizer to access properties
+associated with the object through weak tables.
+
+
+
+If a weak table is among the resurrected objects in a collection cycle,
+it may not be properly cleared until the next cycle.
+
+
+
+
+
+
+
+
+Lua supports coroutines,
+also called collaborative multithreading.
+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.
+
+
+
+You create a coroutine by calling coroutine.create.
+Its sole argument is a function
+that is the main function of the coroutine.
+The create function only creates a new coroutine and
+returns a handle to it (an object of type thread);
+it does not start the coroutine.
+
+
+
+You execute a coroutine by calling coroutine.resume.
+When you first call coroutine.resume,
+passing as its first argument
+a thread returned by coroutine.create,
+the coroutine starts its execution,
+at the first line of its main function.
+Extra arguments passed to coroutine.resume are passed
+as arguments to the coroutine's main function.
+After the coroutine starts running,
+it runs until it terminates or yields.
+
+
+
+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 case of normal termination,
+coroutine.resume returns true,
+plus any values returned by the coroutine main function.
+In case of errors, coroutine.resume returns false
+plus an error message.
+
+
+
+A coroutine yields by calling coroutine.yield.
+When a coroutine yields,
+the corresponding coroutine.resume 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, coroutine.resume also returns true,
+plus any values passed to coroutine.yield.
+The next time you resume the same coroutine,
+it continues its execution from the point where it yielded,
+with the call to coroutine.yield returning any extra
+arguments passed to coroutine.resume.
+
+
+
+Like coroutine.create,
+the coroutine.wrap function also creates a coroutine,
+but instead of returning the coroutine itself,
+it returns a function that, when called, resumes the coroutine.
+Any arguments passed to this function
+go as extra arguments to coroutine.resume.
+coroutine.wrap returns all the values returned by coroutine.resume,
+except the first one (the boolean error code).
+Unlike coroutine.resume,
+coroutine.wrap does not catch errors;
+any error is propagated to the caller.
+
+
+
+As an example of how coroutines work,
+consider the following code:
+
+
+ function foo (a)
+ print("foo", a)
+ return coroutine.yield(2*a)
+ end
+
+ co = coroutine.create(function (a,b)
+ print("co-body", a, b)
+ local r = foo(a+1)
+ print("co-body", r)
+ local r, s = coroutine.yield(a+b, a-b)
+ print("co-body", r, s)
+ return b, "end"
+ end)
+
+ print("main", coroutine.resume(co, 1, 10))
+ print("main", coroutine.resume(co, "r"))
+ print("main", coroutine.resume(co, "x", "y"))
+ print("main", coroutine.resume(co, "x", "y"))
+
+When you run it, it produces the following output:
+
+
+ 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
+
+
+
+You can also create and manipulate coroutines through the C API:
+see functions lua_newthread, lua_resume,
+and lua_yield.
+
+
+
+
+
+
+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.
+
+
+
+Language constructs will be explained using the usual extended BNF notation,
+in which
+{a} means 0 or more a's, and
+[a] means an optional a.
+Non-terminals are shown like non-terminal,
+keywords are shown like kword,
+and other terminal symbols are shown like ‘=’.
+The complete syntax of Lua can be found in §9
+at the end of this manual.
+
+
+
+
+Lua is a free-form language.
+It ignores spaces (including new lines) and comments
+between lexical elements (tokens),
+except as delimiters between names and keywords.
+
+
+
+Names
+(also called identifiers)
+in Lua can be any string of letters,
+digits, and underscores,
+not beginning with a digit.
+Identifiers are used to name variables, table fields, and labels.
+
+
+
+The following keywords are reserved
+and cannot be used as names:
+
+
+
+ and break do else elseif end
+ false for function goto if in
+ local nil not or repeat return
+ then true until while
+
+
+
+Lua is a case-sensitive language:
+and is a reserved word, but And and AND
+are two different, valid names.
+As a convention,
+programs should avoid creating
+names that start with an underscore followed by
+one or more uppercase letters (such as _VERSION).
+
+
+
+Literal strings
+can be delimited by matching single or double quotes,
+and can contain the following C-like escape sequences:
+'\a' (bell),
+'\b' (backspace),
+'\f' (form feed),
+'\n' (newline),
+'\r' (carriage return),
+'\t' (horizontal tab),
+'\v' (vertical tab),
+'\\' (backslash),
+'\"' (quotation mark [double quote]),
+and '\'' (apostrophe [single quote]).
+A backslash followed by a real newline
+results in a newline in the string.
+The escape sequence '\z' skips the following span
+of white-space characters,
+including line breaks;
+it is particularly useful to break and indent a long literal string
+into multiple lines without adding the newlines and spaces
+into the string contents.
+
+
+
+Strings in Lua can contain any 8-bit value, including embedded zeros,
+which can be specified as '\0'.
+More generally,
+we can specify any byte in a literal string by its numerical value.
+This can be done
+with the escape sequence \xXX,
+where XX is a sequence of exactly two hexadecimal digits,
+or with the escape sequence \ddd,
+where ddd is a sequence of up to three decimal digits.
+(Note that if a decimal escape sequence is to be followed by a digit,
+it must be expressed using exactly three digits.)
+
+
+
+The UTF-8 encoding of a Unicode character
+can be inserted in a literal string with
+the escape sequence \u{XXX}
+(note the mandatory enclosing brackets),
+where XXX is a sequence of one or more hexadecimal digits
+representing the character code point.
+
+
+
+Literal strings can also be defined using a long format
+enclosed by long brackets.
+We define an opening long bracket of level n as an opening
+square bracket followed by n equal signs followed by another
+opening square bracket.
+So, an opening long bracket of level 0 is written as [[,
+an opening long bracket of level 1 is written as [=[,
+and so on.
+A closing long bracket is defined similarly;
+for instance,
+a closing long bracket of level 4 is written as ]====].
+A long literal starts with an opening long bracket of any level and
+ends at the first closing long bracket of the same level.
+It can contain any text except a closing bracket of the same level.
+Literals in this bracketed form can run for several lines,
+do not interpret any escape sequences,
+and ignore long brackets of any other level.
+Any kind of end-of-line sequence
+(carriage return, newline, carriage return followed by newline,
+or newline followed by carriage return)
+is converted to a simple newline.
+
+
+
+Any byte in a literal string not
+explicitly affected by the previous rules represents itself.
+However, Lua opens files for parsing in text mode,
+and the system file functions may have problems with
+some control characters.
+So, it is safer to represent
+non-text data as a quoted literal with
+explicit escape sequences for non-text characters.
+
+
+
+For convenience,
+when the opening long 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 'a' is coded as 97,
+newline is coded as 10, and '1' is coded as 49),
+the five literal strings below denote the same string:
+
+
+ a = 'alo\n123"'
+ a = "alo\n123\""
+ a = '\97lo\10\04923"'
+ a = [[alo
+ 123"]]
+ a = [==[
+ alo
+ 123"]==]
+
+
+
+A numerical constant (or numeral)
+can be written with an optional fractional part
+and an optional decimal exponent,
+marked by a letter 'e' or 'E'.
+Lua also accepts hexadecimal constants,
+which start with 0x or 0X.
+Hexadecimal constants also accept an optional fractional part
+plus an optional binary exponent,
+marked by a letter 'p' or 'P'.
+A numeric constant with a fractional dot or an exponent
+denotes a float;
+otherwise it denotes an integer.
+Examples of valid integer constants are
+
+
+A comment starts with a double hyphen (--)
+anywhere outside a string.
+If the text immediately after -- is not an opening long bracket,
+the comment is a short comment,
+which runs until the end of the line.
+Otherwise, it is a long comment,
+which runs until the corresponding closing long bracket.
+Long comments are frequently used to disable code temporarily.
+
+
+
+
+
+
+Variables are places that store values.
+There are three kinds of variables in Lua:
+global variables, local variables, and table fields.
+
+
+
+A single name can denote a global variable or a local variable
+(or a function's formal parameter,
+which is a particular kind of local variable):
+
+
+ var ::= Name
+
+Name denotes identifiers, as defined in §3.1.
+
+
+
+Any variable name is assumed to be global unless explicitly declared
+as a local (see §3.3.7).
+Local variables are lexically scoped:
+local variables can be freely accessed by functions
+defined inside their scope (see §3.5).
+
+
+
+Before the first assignment to a variable, its value is nil.
+
+
+
+Square brackets are used to index a table:
+
+
+ var ::= prefixexp ‘[’ exp ‘]’
+
+The meaning of accesses to table fields can be changed via metatables.
+An access to an indexed variable t[i] is equivalent to
+a call gettable_event(t,i).
+(See §2.4 for a complete description of the
+gettable_event function.
+This function is not defined or callable in Lua.
+We use it here only for explanatory purposes.)
+
+
+
+The syntax var.Name is just syntactic sugar for
+var["Name"]:
+
+
+ var ::= prefixexp ‘.’ Name
+
+
+
+An access to a global variable x
+is equivalent to _ENV.x.
+Due to the way that chunks are compiled,
+_ENV is never a global name (see §2.2).
+
+
+
+
+
+
+Lua supports an almost conventional set of statements,
+similar to those in Pascal or C.
+This set includes
+assignments, control structures, function calls,
+and variable declarations.
+
+
+
+
+A block is a list of statements,
+which are executed sequentially:
+
+
+ block ::= {stat}
+
+Lua has empty statements
+that allow you to separate statements with semicolons,
+start a block with a semicolon
+or write two semicolons in sequence:
+
+
+ stat ::= ‘;’
+
+
+
+Function calls and assignments
+can start with an open parenthesis.
+This possibility leads to an ambiguity in Lua's grammar.
+Consider the following fragment:
+
+
+ a = b + c
+ (print or io.write)('done')
+
+The grammar could see it in two ways:
+
+
+ a = b + c(print or io.write)('done')
+
+ a = b + c; (print or io.write)('done')
+
+The current parser always sees such constructions
+in the first way,
+interpreting the open parenthesis
+as the start of the arguments to a call.
+To avoid this ambiguity,
+it is a good practice to always precede with a semicolon
+statements that start with a parenthesis:
+
+
+ ;(print or io.write)('done')
+
+
+
+A block can be explicitly delimited to produce a single statement:
+
+
+ stat ::= do block end
+
+Explicit blocks are useful
+to control the scope of variable declarations.
+Explicit blocks are also sometimes used to
+add a return statement in the middle
+of another block (see §3.3.4).
+
+
+
+
+
+
+The unit of compilation of Lua is called a chunk.
+Syntactically,
+a chunk is simply a block:
+
+
+ chunk ::= block
+
+
+
+Lua handles a chunk as the body of an anonymous function
+with a variable number of arguments
+(see §3.4.11).
+As such, chunks can define local variables,
+receive arguments, and return values.
+Moreover, such anonymous function is compiled as in the
+scope of an external local variable called _ENV (see §2.2).
+The resulting function always has _ENV as its only upvalue,
+even if it does not use that variable.
+
+
+
+A chunk can be stored in a file or in a string inside the host program.
+To execute a chunk,
+Lua first loads it,
+precompiling the chunk's code into instructions for a virtual machine,
+and then Lua executes the compiled code
+with an interpreter for the virtual machine.
+
+
+
+Chunks can also be precompiled into binary form;
+see program luac and function string.dump for details.
+Programs in source and compiled forms are interchangeable;
+Lua automatically detects the file type and acts accordingly (see load).
+
+
+
+
+
+
+Lua allows multiple assignments.
+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:
+
+
+ stat ::= varlist ‘=’ explist
+ varlist ::= var {‘,’ var}
+ explist ::= exp {‘,’ exp}
+
+Before the assignment,
+the list of values is adjusted 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 nil's as needed.
+If the list of expressions ends with a function call,
+then all values returned by that call enter the list of values,
+before the adjustment
+(except when the call is enclosed in parentheses; see §3.4).
+
+
+
+The assignment statement first evaluates all its expressions
+and only then the assignments are performed.
+Thus the code
+
+
+ i = 3
+ i, a[i] = i+1, 20
+
+sets a[3] to 20, without affecting a[4]
+because the i in a[i] is evaluated (to 3)
+before it is assigned 4.
+Similarly, the line
+
+
+ x, y = y, x
+
+exchanges the values of x and y,
+and
+
+
+ x, y, z = y, z, x
+
+cyclically permutes the values of x, y, and z.
+
+
+
+The meaning of assignments to global variables
+and table fields can be changed via metatables.
+An assignment to an indexed variable t[i] = val is equivalent to
+settable_event(t,i,val).
+(See §2.4 for a complete description of the
+settable_event function.
+This function is not defined or callable in Lua.
+We use it here only for explanatory purposes.)
+
+
+
+An assignment to a global name x = val
+is equivalent to the assignment
+_ENV.x = val (see §2.2).
+
+
+
+
+
+
+The control structures
+if, while, and repeat have the usual meaning and
+familiar syntax:
+
+
+
+
+
+ stat ::= while exp do block end
+ stat ::= repeat block until exp
+ stat ::= if exp then block {elseif exp then block} [else block] end
+
+Lua also has a for statement, in two flavors (see §3.3.5).
+
+
+
+The condition expression of a
+control structure can return any value.
+Both false and nil are considered false.
+All values different from nil and false are considered true
+(in particular, the number 0 and the empty string are also true).
+
+
+
+In the repeat–until loop,
+the inner block does not end at the until keyword,
+but only after the condition.
+So, the condition can refer to local variables
+declared inside the loop block.
+
+
+
+The goto statement transfers the program control to a label.
+For syntactical reasons,
+labels in Lua are considered statements too:
+
+
+
+
+ stat ::= goto Name
+ stat ::= label
+ label ::= ‘::’ Name ‘::’
+
+
+
+A label is visible in the entire block where it is defined,
+except
+inside nested blocks where a label with the same name is defined and
+inside nested functions.
+A goto may jump to any visible label as long as it does not
+enter into the scope of a local variable.
+
+
+
+Labels and empty statements are called void statements,
+as they perform no actions.
+
+
+
+The break statement terminates the execution of a
+while, repeat, or for loop,
+skipping to the next statement after the loop:
+
+
+
+ stat ::= break
+
+A break ends the innermost enclosing loop.
+
+
+
+The return statement is used to return values
+from a function or a chunk
+(which is an anonymous function).
+
+Functions can return more than one value,
+so the syntax for the return statement is
+
+
+ stat ::= return [explist] [‘;’]
+
+
+
+The return statement can only be written
+as the last statement of a block.
+If it is really necessary to return in the middle of a block,
+then an explicit inner block can be used,
+as in the idiom do return end,
+because now return is the last statement in its (inner) block.
+
+
+
+
+
+
+
+The for statement has two forms:
+one numeric and one generic.
+
+
+
+The numeric for loop repeats a block of code while a
+control variable runs through an arithmetic progression.
+It has the following syntax:
+
+
+ stat ::= for Name ‘=’ exp ‘,’ exp [‘,’ exp] do block end
+
+The block is repeated for name starting at the value of
+the first exp, until it passes the second exp by steps of the
+third exp.
+More precisely, a for statement like
+
+
+ for v = e1, e2, e3 do block end
+
+is equivalent to the code:
+
+
+ do
+ local var, limit, step = tonumber(e1), tonumber(e2), tonumber(e3)
+ if not (var and limit and step) then error() end
+ var = var - step
+ while true do
+ var = var + step
+ if (step >= 0 and var > limit) or (step < 0 and var < limit) then
+ break
+ end
+ local v = var
+ block
+ end
+ end
+
+
+
+Note the following:
+
+
+
+
+All three control expressions are evaluated only once,
+before the loop starts.
+They must all result in numbers.
+
+
+
+var, limit, and step are invisible variables.
+The names shown here are for explanatory purposes only.
+
+
+
+If the third expression (the step) is absent,
+then a step of 1 is used.
+
+
+
+You can use break and goto to exit a for loop.
+
+
+
+The loop variable v is local to the loop body.
+If you need its value after the loop,
+assign it to another variable before exiting the loop.
+
+
+
+
+
+The generic for statement works over functions,
+called iterators.
+On each iteration, the iterator function is called to produce a new value,
+stopping when this new value is nil.
+The generic for loop has the following syntax:
+
+
+ stat ::= for namelist in explist do block end
+ namelist ::= Name {‘,’ Name}
+
+A for statement like
+
+
+ for var_1, ···, var_n in explist do block end
+
+is equivalent to the code:
+
+
+ do
+ local f, s, var = explist
+ while true do
+ local var_1, ···, var_n = f(s, var)
+ if var_1 == nil then break end
+ var = var_1
+ block
+ end
+ end
+
+Note the following:
+
+
+
+
+explist is evaluated only once.
+Its results are an iterator function,
+a state,
+and an initial value for the first iterator variable.
+
+
+
+f, s, and var are invisible variables.
+The names are here for explanatory purposes only.
+
+
+
+You can use break to exit a for loop.
+
+
+
+The loop variables var_i are local to the loop;
+you cannot use their values after the for ends.
+If you need these values,
+then assign them to other variables before breaking or exiting the loop.
+
+Local variables can be declared anywhere inside a block.
+The declaration can include an initial assignment:
+
+
+ stat ::= local namelist [‘=’ explist]
+
+If present, an initial assignment has the same semantics
+of a multiple assignment (see §3.3.3).
+Otherwise, all variables are initialized with nil.
+
+
+
+A chunk is also a block (see §3.3.2),
+and so local variables can be declared in a chunk outside any explicit block.
+
+
+
+The visibility rules for local variables are explained in §3.5.
+
+
+
+
+
+
+
+
+Numerals and literal strings are explained in §3.1;
+variables are explained in §3.2;
+function definitions are explained in §3.4.11;
+function calls are explained in §3.4.10;
+table constructors are explained in §3.4.9.
+Vararg expressions,
+denoted by three dots ('...'), can only be used when
+directly inside a vararg function;
+they are explained in §3.4.11.
+
+
+
+Binary operators comprise arithmetic operators (see §3.4.1),
+bitwise operators (see §3.4.2),
+relational operators (see §3.4.4), logical operators (see §3.4.5),
+and the concatenation operator (see §3.4.6).
+Unary operators comprise the unary minus (see §3.4.1),
+the unary bitwise not (see §3.4.2),
+the unary logical not (see §3.4.5),
+and the unary length operator (see §3.4.7).
+
+
+
+Both function calls and vararg expressions can result in multiple values.
+If a function call is used as a statement (see §3.3.6),
+then its return list is adjusted to zero elements,
+thus discarding all returned values.
+If an expression is used as the last (or the only) element
+of a list of expressions,
+then no adjustment is made
+(unless the expression is enclosed in parentheses).
+In all other contexts,
+Lua adjusts the result list to one element,
+either discarding all values except the first one
+or adding a single nil if there are no values.
+
+
+
+Here are some examples:
+
+
+ f() -- adjusted to 0 results
+ g(f(), x) -- f() is adjusted to 1 result
+ g(x, f()) -- g gets x plus all results from 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 can 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 results from f()
+ return ... -- returns all received vararg parameters
+ return x,y,f() -- returns x, y, and all results from f()
+ {f()} -- creates a list with all results from f()
+ {...} -- creates a list with all vararg parameters
+ {f(), nil} -- f() is adjusted to 1 result
+
+
+
+Any expression enclosed in parentheses always results in only one value.
+Thus,
+(f(x,y,z)) is always a single value,
+even if f returns several values.
+(The value of (f(x,y,z)) is the first value returned by f
+or nil if f does not return any values.)
+
+
+
+
+Lua supports the following arithmetic operators:
+
+
+
+: addition
+
-: subtraction
+
*: multiplication
+
/: float division
+
//: floor division
+
%: modulo
+
^: exponentiation
+
-: unary minus
+
+
+
+With the exception of exponentiation and float division,
+the arithmetic operators work as follows:
+If both operands are integers,
+the operation is performed over integers and the result is an integer.
+Otherwise, if both operands are numbers
+or strings that can be converted to
+numbers (see §3.4.3),
+then they are converted to floats,
+the operation is performed following the usual rules
+for floating-point arithmetic
+(usually the IEEE 754 standard),
+and the result is a float.
+
+
+
+Exponentiation and float division (/)
+always convert their operands to floats
+and the result is always a float.
+Exponentiation uses the ISO C function pow,
+so that it works for non-integer exponents too.
+
+
+
+Floor division (//) is a division
+that rounds the quotient towards minus infinite,
+that is, the floor of the division of its operands.
+
+
+
+Modulo is defined as the remainder of a division
+that rounds the quotient towards minus infinite (floor division).
+
+
+
+In case of overflows in integer arithmetic,
+all operations wrap around,
+according to the usual rules of two-complement arithmetic.
+(In other words,
+they return the unique representable integer
+that is equal modulo 264 to the mathematical result.)
+
+
+
+
+Lua supports the following bitwise operators:
+
+
+
&: bitwise and
+
|: bitwise or
+
~: bitwise exclusive or
+
>>: right shift
+
<<: left shift
+
~: unary bitwise not
+
+
+
+All bitwise operations convert its operands to integers
+(see §3.4.3),
+operate on all bits of those integers,
+and result in an integer.
+
+
+
+Both right and left shifts fill the vacant bits with zeros.
+Negative displacements shift to the other direction;
+displacements with absolute values equal to or higher than
+the number of bits in an integer
+result in zero (as all bits are shifted out).
+
+
+
+
+
+
+Lua provides some automatic conversions between some
+types and representations at run time.
+Bitwise operators always convert float operands to integers.
+Exponentiation and float division
+always convert integer operands to floats.
+All other arithmetic operations applied to mixed numbers
+(integers and floats) convert the integer operand to a float;
+this is called the usual rule.
+The C API also converts both integers to floats and
+floats to integers, as needed.
+Moreover, string concatenation accepts numbers as arguments,
+besides strings.
+
+
+
+Lua also converts strings to numbers,
+whenever a number is expected.
+
+
+
+In a conversion from integer to float,
+if the integer value has an exact representation as a float,
+that is the result.
+Otherwise,
+the conversion gets the nearest higher or
+the nearest lower representable value.
+This kind of conversion never fails.
+
+
+
+The conversion from float to integer
+checks whether the float has an exact representation as an integer
+(that is, the float has an integral value and
+it is in the range of integer representation).
+If it does, that representation is the result.
+Otherwise, the conversion fails.
+
+
+
+The conversion from strings to numbers goes as follows:
+First, the string is converted to an integer or a float,
+following its syntax and the rules of the Lua lexer.
+(The string may have also leading and trailing spaces and a sign.)
+Then, the resulting number is converted to the required type
+(float or integer) according to the previous rules.
+
+
+
+The conversion from numbers to strings uses a
+non-specified human-readable format.
+For complete control over how numbers are converted to strings,
+use the format function from the string library
+(see string.format).
+
+
+
+
+
+
+Lua supports the following relational operators:
+
+
+
==: equality
+
~=: inequality
+
<: less than
+
>: greater than
+
<=: less or equal
+
>=: greater or equal
+
+These operators always result in false or true.
+
+
+
+Equality (==) first compares the type of its operands.
+If the types are different, then the result is false.
+Otherwise, the values of the operands are compared.
+Strings are compared in the obvious way.
+Numbers follow the usual rule for binary operations:
+if both operands are integers,
+they are compared as integers;
+otherwise, they are converted to floats
+and compared as such.
+
+
+
+Tables, userdata, and threads
+are compared by reference:
+two objects are considered equal only if they are the same object.
+Every time you create a new object
+(a table, userdata, or thread),
+this new object is different from any previously existing object.
+Closures with the same reference are always equal.
+Closures with any detectable difference
+(different behavior, different definition) are always different.
+
+
+
+You can change the way that Lua compares tables and userdata
+by using the "eq" metamethod (see §2.4).
+
+
+
+Equality comparisons do not convert strings to numbers
+or vice versa.
+Thus, "0"==0 evaluates to false,
+and t[0] and t["0"] denote different
+entries in a table.
+
+
+
+The operator ~= is exactly the negation of equality (==).
+
+
+
+The order operators work as follows.
+If both arguments are numbers,
+then they are compared following
+the usual rule for binary operations.
+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 §2.4).
+A comparison a > b is translated to b < a
+and a >= b is translated to b <= a.
+
+
+
+
+
+
+The logical operators in Lua are
+and, or, and not.
+Like the control structures (see §3.3.4),
+all logical operators consider both false and nil as false
+and anything else as true.
+
+
+
+The negation operator not always returns false or true.
+The conjunction operator and returns its first argument
+if this value is false or nil;
+otherwise, and returns its second argument.
+The disjunction operator or returns its first argument
+if this value is different from nil and false;
+otherwise, or returns its second argument.
+Both and and or use short-circuit evaluation;
+that is,
+the second operand is evaluated only if necessary.
+Here are some examples:
+
+
+ 10 or 20 --> 10
+ 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
+
+(In this manual,
+--> indicates the result of the preceding expression.)
+
+
+
+
+
+
+The string concatenation operator in Lua is
+denoted by two dots ('..').
+If both operands are strings or numbers, then they are converted to
+strings according to the rules described in §3.4.3.
+Otherwise, the __concat metamethod is called (see §2.4).
+
+
+
+
+
+
+The length operator is denoted by the unary prefix operator #.
+The length of a string is its number of bytes
+(that is, the usual meaning of string length when each
+character is one byte).
+
+
+
+A program can modify the behavior of the length operator for
+any value but strings through the __len metamethod (see §2.4).
+
+
+
+Unless a __len metamethod is given,
+the length of a table t is only defined if the
+table is a sequence,
+that is,
+the set of its positive numeric keys is equal to {1..n}
+for some non-negative integer n.
+In that case, n is its length.
+Note that a table like
+
+
+ {10, 20, nil, 40}
+
+is not a sequence, because it has the key 4
+but does not have the key 3.
+(So, there is no n such that the set {1..n} is equal
+to the set of positive numeric keys of that table.)
+Note, however, that non-numeric keys do not interfere
+with whether a table is a sequence.
+
+
+
+
+
+
+As usual,
+you can use parentheses to change the precedences of an expression.
+The concatenation ('..') and exponentiation ('^')
+operators are right associative.
+All other binary operators are left associative.
+
+
+
+
+
+
+Table constructors are expressions that create tables.
+Every time a constructor is evaluated, a new table is created.
+A constructor can be used to create an empty table
+or to create a table and initialize some of its fields.
+The general syntax for constructors is
+
+
+Each field of the form [exp1] = exp2 adds to the new table an entry
+with key exp1 and value exp2.
+A field of the form name = exp is equivalent to
+["name"] = exp.
+Finally, fields of the form exp are equivalent to
+[i] = exp, where i are consecutive integers
+starting with 1.
+Fields in the other formats do not affect this counting.
+For example,
+
+
+ a = { [f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45 }
+
+is equivalent to
+
+
+ do
+ local t = {}
+ t[f(1)] = g
+ t[1] = "x" -- 1st exp
+ t[2] = "y" -- 2nd exp
+ t.x = 1 -- t["x"] = 1
+ t[3] = f(x) -- 3rd exp
+ t[30] = 23
+ t[4] = 45 -- 4th exp
+ a = t
+ end
+
+
+
+The order of the assignments in a constructor is undefined.
+(This order would be relevant only when there are repeated keys.)
+
+
+
+If the last field in the list has the form exp
+and the expression is a function call or a vararg expression,
+then all values returned by this expression enter the list consecutively
+(see §3.4.10).
+
+
+
+The field list can have an optional trailing separator,
+as a convenience for machine-generated code.
+
+
+
+
+
+
+A function call in Lua has the following syntax:
+
+
+ functioncall ::= prefixexp args
+
+In a function call,
+first prefixexp and args are evaluated.
+If the value of prefixexp has type function,
+then this function is called
+with the given arguments.
+Otherwise, the prefixexp "call" metamethod is called,
+having as first parameter the value of prefixexp,
+followed by the original call arguments
+(see §2.4).
+
+
+
+The form
+
+
+ functioncall ::= prefixexp ‘:’ Name args
+
+can be used to call "methods".
+A call v:name(args)
+is syntactic sugar for v.name(v,args),
+except that v is evaluated only once.
+
+
+
+All argument expressions are evaluated before the call.
+A call of the form f{fields} is
+syntactic sugar for f({fields});
+that is, the argument list is a single new table.
+A call of the form f'string'
+(or f"string" or f[[string]])
+is syntactic sugar for f('string');
+that is, the argument list is a single literal string.
+
+
+
+A call of the form return functioncall is called
+a tail call.
+Lua implements proper tail calls
+(or proper tail recursion):
+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 return has one single function call as argument;
+this syntax makes the calling function return exactly
+the returns of the called function.
+So, none of the following examples are tail calls:
+
+
+ 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
+
+ functiondef ::= function funcbody
+ funcbody ::= ‘(’ [parlist] ‘)’ block end
+
+
+
+The following syntactic sugar simplifies function definitions:
+
+
+ stat ::= function funcname funcbody
+ stat ::= localfunction Name funcbody
+ funcname ::= Name {‘.’ Name} [‘:’ Name]
+
+The statement
+
+
+ function f () body end
+
+translates to
+
+
+ f = function () body end
+
+The statement
+
+
+ function t.a.b.c.f () body end
+
+translates to
+
+
+ t.a.b.c.f = function () body end
+
+The statement
+
+
+ local function f () body end
+
+translates to
+
+
+ local f; f = function () body end
+
+not to
+
+
+ local f = function () body end
+
+(This only makes a difference when the body of the function
+contains references to f.)
+
+
+
+A function definition is an executable expression,
+whose value has type function.
+When Lua precompiles a chunk,
+all its function bodies are precompiled too.
+Then, whenever Lua executes the function definition,
+the function is instantiated (or closed).
+This function instance (or closure)
+is the final value of the expression.
+
+
+
+Parameters act as local variables that are
+initialized with the argument values:
+
+
+ parlist ::= namelist [‘,’ ‘...’] | ‘...’
+
+When a function is called,
+the list of arguments is adjusted to
+the length of the list of parameters,
+unless the function is a vararg function,
+which is indicated by three dots ('...')
+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 vararg expression,
+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 that last expression is enclosed in parentheses).
+
+
+
+As an example, consider the following definitions:
+
+
+ function f(a, b) end
+ function g(a, b, ...) end
+ function r() return 1,2,3 end
+
+Then, we have the following mapping from arguments to parameters and
+to the vararg expression:
+
+
+Results are returned using the return statement (see §3.3.4).
+If control reaches the end of a function
+without encountering a return statement,
+then the function returns with no results.
+
+
+
+
+There is a system-dependent limit on the number of values
+that a function may return.
+This limit is guaranteed to be larger than 1000.
+
+
+
+The colon syntax
+is used for defining methods,
+that is, functions that have an implicit extra parameter self.
+Thus, the statement
+
+
+
+Lua is a lexically scoped language.
+The scope of a local variable begins at the first statement after
+its declaration and lasts until the last non-void statement
+of the innermost block that includes the declaration.
+Consider the following example:
+
+
+ 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)
+
+
+
+Notice that, in a declaration like local x = x,
+the new x being declared is not in scope yet,
+and so the second x refers to the outside variable.
+
+
+
+Because of the lexical scoping rules,
+local variables can be freely accessed by functions
+defined inside their scope.
+A local variable used by an inner function is called
+an upvalue, or external local variable,
+inside the inner function.
+
+
+
+Notice that each execution of a local statement
+defines new local variables.
+Consider the following example:
+
+
+ a = {}
+ local x = 20
+ for i=1,10 do
+ local y = 0
+ a[i] = function () y=y+1; return x+y end
+ end
+
+The loop creates ten closures
+(that is, ten instances of the anonymous function).
+Each of these closures uses a different y variable,
+while all of them share the same x.
+
+
+
+
+
+
+
+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 lua.h.
+
+
+
+Even when we use the term "function",
+any facility in the API may be provided as a macro instead.
+Except where stated otherwise,
+all such macros use each of their arguments exactly once
+(except for the first argument, which is always a Lua state),
+and so do not generate any hidden side-effects.
+
+
+
+As in most C libraries,
+the Lua API functions do not check their arguments for validity or consistency.
+However, you can change this behavior by compiling Lua
+with the macro LUA_USE_APICHECK defined.
+
+
+
+
+Lua uses a virtual stack to pass values to and from C.
+Each element in this stack represents a Lua value
+(nil, number, string, etc.).
+
+
+
+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.
+This 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 lua_CFunction).
+
+
+
+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 index:
+A positive index represents an absolute stack position
+(starting at 1);
+a negative index represents an offset relative to the top of the stack.
+More specifically, if the stack has n elements,
+then index 1 represents the first element
+(that is, the element that was pushed onto the stack first)
+and
+index n represents the last element;
+index -1 also represents the last element
+(that is, the element at the top)
+and index -n represents the first element.
+
+
+
+
+
+
+When you interact with the Lua API,
+you are responsible for ensuring consistency.
+In particular,
+you are responsible for controlling stack overflow.
+You can use the function lua_checkstack
+to ensure that the stack has enough space for pushing new elements.
+
+
+
+Whenever Lua calls C,
+it ensures that the stack has space for
+at least LUA_MINSTACK extra slots.
+LUA_MINSTACK 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.
+
+
+
+When you call a Lua function
+without a fixed number of results (see lua_call),
+Lua ensures that the stack has enough space for all results,
+but it does not ensure any extra space.
+So, before pushing anything in the stack after such a call
+you should use lua_checkstack.
+
+
+
+
+
+
+Any function in the API that receives stack indices
+works only with valid indices or acceptable indices.
+
+
+
+A valid index is an index that refers to a
+real position within the stack, that is,
+its position lies between 1 and the stack top
+(1 ≤ abs(index) ≤ top).
+
+Usually, functions that can modify the value at an index
+require valid indices.
+
+
+
+Unless otherwise noted,
+any function that accepts valid indices also accepts pseudo-indices,
+which represent some Lua values that are accessible to C code
+but which are not in the stack.
+Pseudo-indices are used to access the registry
+and the upvalues of a C function (see §4.4).
+
+
+
+Functions that do not need a specific stack position,
+but only a value in the stack (e.g., query functions),
+can be called with acceptable indices.
+An acceptable index can be any valid index,
+including the pseudo-indices,
+but it also can be any positive index after the stack top
+within the space allocated for the stack,
+that is, indices up to the stack size.
+(Note that 0 is never an acceptable index.)
+Except when noted otherwise,
+functions in the API work with acceptable indices.
+
+
+
+Acceptable indices serve to avoid extra tests
+against the stack top when querying the stack.
+For instance, a C function can query its third argument
+without the need to first check whether there is a third argument,
+that is, without the need to check whether 3 is a valid index.
+
+
+
+For functions that can be called with acceptable indices,
+any non-valid index is treated as if it
+contains a value of a virtual type LUA_TNONE,
+which behaves like a nil value.
+
+
+
+
+
+
+When a C function is created,
+it is possible to associate some values with it,
+thus creating a C closure
+(see lua_pushcclosure);
+these values are called upvalues and are
+accessible to the function whenever it is called.
+
+
+
+Whenever a C function is called,
+its upvalues are located at specific pseudo-indices.
+These pseudo-indices are produced by the macro
+lua_upvalueindex.
+The first value associated with a function is at position
+lua_upvalueindex(1), and so on.
+Any access to lua_upvalueindex(n),
+where n is greater than the number of upvalues of the
+current function (but not greater than 256),
+produces an acceptable but invalid index.
+
+
+
+
+
+
+Lua provides a registry,
+a predefined table that can be used by any C code to
+store whatever Lua values it needs to store.
+The registry table is always located at pseudo-index
+LUA_REGISTRYINDEX,
+which is a valid index.
+Any C library can store data into this table,
+but it must take care to choose keys
+that are different from those used
+by other libraries, to avoid collisions.
+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,
+or any Lua object created by your code.
+As with variable names,
+string keys starting with an underscore followed by
+uppercase letters are reserved for Lua.
+
+
+
+The integer keys in the registry are used
+by the reference mechanism (see luaL_ref)
+and by some predefined values.
+Therefore, integer keys must not be used for other purposes.
+
+
+
+When you create a new Lua state,
+its registry comes with some predefined values.
+These predefined values are indexed with integer keys
+defined as constants in lua.h.
+The following constants are defined:
+
+
+
LUA_RIDX_MAINTHREAD: At this index the registry has
+the main thread of the state.
+(The main thread is the one created together with the state.)
+
+
+
LUA_RIDX_GLOBALS: At this index the registry has
+the global environment.
+
+Internally, Lua uses the C longjmp facility to handle errors.
+(Lua will use exceptions if you compile it as C++;
+search for LUAI_THROW in the source code for details.)
+When Lua faces any error
+(such as a memory allocation error, type errors, syntax errors,
+and runtime errors)
+it raises an error;
+that is, it does a long jump.
+A protected environment uses setjmp
+to set a recovery point;
+any error jumps to the most recent active recovery point.
+
+
+
+If an error happens outside any protected environment,
+Lua calls a panic function (see lua_atpanic)
+and then calls abort,
+thus exiting the host application.
+Your panic function can avoid this exit by
+never returning
+(e.g., doing a long jump to your own recovery point outside Lua).
+
+
+
+The panic function runs as if it were a message handler (see §2.3);
+in particular, the error message is at the top of the stack.
+However, there is no guarantee about stack space.
+To push anything on the stack,
+the panic function must first check the available space (see §4.2).
+
+
+
+Most functions in the API can raise an error,
+for instance due to a memory allocation error.
+The documentation for each function indicates whether
+it can raise errors.
+
+
+
+Inside a C function you can raise an error by calling lua_error.
+
+
+
+
+
+
+Internally, Lua uses the C longjmp facility to yield a coroutine.
+Therefore, if a C function foo calls an API function
+and this API function yields
+(directly or indirectly by calling another function that yields),
+Lua cannot return to foo any more,
+because the longjmp removes its frame from the C stack.
+
+
+
+To avoid this kind of problem,
+Lua raises an error whenever it tries to yield across an API call,
+except for three functions:
+lua_yieldk, lua_callk, and lua_pcallk.
+All those functions receive a continuation function
+(as a parameter named k) to continue execution after a yield.
+
+
+
+We need to set some terminology to explain continuations.
+We have a C function called from Lua which we will call
+the original function.
+This original function then calls one of those three functions in the C API,
+which we will call the callee function,
+that then yields the current thread.
+(This can happen when the callee function is lua_yieldk,
+or when the callee function is either lua_callk or lua_pcallk
+and the function called by them yields.)
+
+
+
+Suppose the running thread yields while executing the callee function.
+After the thread resumes,
+it eventually will finish running the callee function.
+However,
+the callee function cannot return to the original function,
+because its frame in the C stack was destroyed by the yield.
+Instead, Lua calls a continuation function,
+which was given as an argument to the callee function.
+As the name implies,
+the continuation function should continue the task
+of the original function.
+
+
+
+As an illustration, consider the following function:
+
+
+ int original_function (lua_State *L) {
+ ... /* code 1 */
+ status = lua_pcall(L, n, m, h); /* calls Lua */
+ ... /* code 2 */
+ }
+
+Now we want to allow
+the Lua code being run by lua_pcall to yield.
+First, we can rewrite our function like here:
+
+
+ int k (lua_State *L, int status, lua_KContext ctx) {
+ ... /* code 2 */
+ }
+
+ int original_function (lua_State *L) {
+ ... /* code 1 */
+ return k(L, lua_pcall(L, n, m, h), ctx);
+ }
+
+In the above code,
+the new function k is a
+continuation function (with type lua_KFunction),
+which should do all the work that the original function
+was doing after calling lua_pcall.
+Now, we must inform Lua that it must call k if the Lua code
+being executed by lua_pcall gets interrupted in some way
+(errors or yielding),
+so we rewrite the code as here,
+replacing lua_pcall by lua_pcallk:
+
+
+ int original_function (lua_State *L) {
+ ... /* code 1 */
+ return k(L, lua_pcallk(L, n, m, h, ctx2, k), ctx1);
+ }
+
+Note the external, explicit call to the continuation:
+Lua will call the continuation only if needed, that is,
+in case of errors or resuming after a yield.
+If the called function returns normally without ever yielding,
+lua_pcallk (and lua_callk) will also return normally.
+(Of course, instead of calling the continuation in that case,
+you can do the equivalent work directly inside the original function.)
+
+
+
+Besides the Lua state,
+the continuation function has two other parameters:
+the final status of the call plus the context value (ctx) that
+was passed originally to lua_pcallk.
+(Lua does not use this context value;
+it only passes this value from the original function to the
+continuation function.)
+For lua_pcallk,
+the status is the same value that would be returned by lua_pcallk,
+except that it is LUA_YIELD when being executed after a yield
+(instead of LUA_OK).
+For lua_yieldk and lua_callk,
+the status is always LUA_YIELD when Lua calls the continuation.
+(For these two functions,
+Lua will not call the continuation in case of errors,
+because they do not handle errors.)
+Similarly, when using lua_callk,
+you should call the continuation function
+with LUA_OK as the status.
+(For lua_yieldk, there is not much point in calling
+directly the continuation function,
+because lua_yieldk usually does not return.)
+
+
+
+Lua treats the continuation function as if it were the original function.
+The continuation function receives the same Lua stack
+from the original function,
+in the same state it would be if the callee function had returned.
+(For instance,
+after a lua_callk the function and its arguments are
+removed from the stack and replaced by the results from the call.)
+It also has the same upvalues.
+Whatever it returns is handled by Lua as if it were the return
+of the original function.
+
+
+
+
+
+
+Here we list all functions and types from the C API in
+alphabetical order.
+Each function has an indicator like this:
+[-o, +p, x]
+
+
+
+The first field, o,
+is how many elements the function pops from the stack.
+The second field, p,
+is how many elements the function pushes onto the stack.
+(Any function always pushes its results after popping its arguments.)
+A field in the form x|y means the function can push (or pop)
+x or y elements,
+depending on the situation;
+an interrogation mark '?' means that
+we cannot know how many elements the function pops/pushes
+by looking only at its arguments
+(e.g., they may depend on what is on the stack).
+The third field, x,
+tells whether the function may raise errors:
+'-' means the function never raises any error;
+'e' means the function may raise errors;
+'v' means the function may raise an error on purpose.
+
+
+
+
+The type of the memory-allocation function used by Lua states.
+The allocator function must provide a
+functionality similar to realloc,
+but not exactly the same.
+Its arguments are
+ud, an opaque pointer passed to lua_newstate;
+ptr, a pointer to the block being allocated/reallocated/freed;
+osize, the original size of the block or some code about what
+is being allocated;
+and nsize, the new size of the block.
+
+
+
+When ptr is not NULL,
+osize is the size of the block pointed by ptr,
+that is, the size given when it was allocated or reallocated.
+
+
+
+When ptr is NULL,
+osize encodes the kind of object that Lua is allocating.
+osize is any of
+LUA_TSTRING, LUA_TTABLE, LUA_TFUNCTION,
+LUA_TUSERDATA, or LUA_TTHREAD when (and only when)
+Lua is creating a new object of that type.
+When osize is some other value,
+Lua is allocating memory for something else.
+
+
+
+Lua assumes the following behavior from the allocator function:
+
+
+
+When nsize is zero,
+the allocator must behave like free
+and return NULL.
+
+
+
+When nsize is not zero,
+the allocator must behave like realloc.
+The allocator returns NULL
+if and only if it cannot fulfill the request.
+Lua assumes that the allocator never fails when
+osize >= nsize.
+
+
+
+Here is a simple implementation for the allocator function.
+It is used in the auxiliary library by luaL_newstate.
+
+
+Note that Standard C ensures
+that free(NULL) has no effect and that
+realloc(NULL,size) is equivalent to malloc(size).
+This code assumes that realloc does not fail when shrinking a block.
+(Although Standard C does not ensure this behavior,
+it seems to be a safe assumption.)
+
+
+
+
+
+
+Performs an arithmetic or bitwise operation over the two values
+(or one, in the case of negations)
+at the top of the stack,
+with the value at the top being the second operand,
+pops these values, and pushes the result of the operation.
+The function follows the semantics of the corresponding Lua operator
+(that is, it may call metamethods).
+
+
+
+The value of op must be one of the following constants:
+
+
void lua_call (lua_State *L, int nargs, int nresults);
+
+
+Calls a function.
+
+
+
+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 lua_call;
+nargs is the number of arguments that you pushed onto the stack.
+All arguments and the function value are popped from the stack
+when the function is called.
+The function results are pushed onto the stack when the function returns.
+The number of results is adjusted to nresults,
+unless nresults is LUA_MULTRET.
+In this case, all 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 of the stack.
+
+
+
+Any error inside the called function is propagated upwards
+(with a longjmp).
+
+
+
+The following example shows how the host program can do the
+equivalent to this Lua code:
+
+
+ a = f("how", t.x, 14)
+
+Here it is in C:
+
+
+ lua_getglobal(L, "f"); /* function to be called */
+ lua_pushliteral(L, "how"); /* 1st argument */
+ lua_getglobal(L, "t"); /* table to be indexed */
+ lua_getfield(L, -1, "x"); /* push result of t.x (2nd arg) */
+ lua_remove(L, -2); /* remove 't' from the stack */
+ lua_pushinteger(L, 14); /* 3rd argument */
+ lua_call(L, 3, 1); /* call 'f' with 3 arguments and 1 result */
+ lua_setglobal(L, "a"); /* set global 'a' */
+
+Note that the code above is balanced:
+at its end, the stack is back to its original configuration.
+This is considered good programming practice.
+
+
+
+
+
+
+In order to communicate properly with Lua,
+a C function must use 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,
+lua_gettop(L) returns the number of arguments received by the function.
+The first argument (if any) is at index 1
+and its last argument is at index lua_gettop(L).
+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
+discarded by Lua.
+Like a Lua function, a C function called by Lua can also return
+many results.
+
+
+
+As an example, the following function receives a variable number
+of numerical arguments and returns their average and their sum:
+
+
+ static int foo (lua_State *L) {
+ int n = lua_gettop(L); /* number of arguments */
+ lua_Number sum = 0.0;
+ int i;
+ for (i = 1; i <= n; i++) {
+ if (!lua_isnumber(L, i)) {
+ lua_pushliteral(L, "incorrect argument");
+ 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 */
+ }
+
+Ensures that the stack has space for at least n extra slots.
+It returns false if it cannot fulfill the request,
+either because it would cause the stack
+to be larger than a fixed maximum size
+(typically at least several thousand elements) or
+because it cannot allocate memory for the extra space.
+This function never shrinks the stack;
+if the stack is already larger than the new size,
+it is left unchanged.
+
+
+
+
+
+
+Destroys all objects in the given Lua state
+(calling the corresponding garbage-collection metamethods, if any)
+and frees all dynamic memory used by this 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 that create multiple states,
+such as daemons or web servers,
+will probably need to close states as soon as they are not needed.
+
+
+
+
+
+
int lua_compare (lua_State *L, int index1, int index2, int op);
+
+
+Compares two Lua values.
+Returns 1 if the value at index index1 satisfies op
+when compared with the value at index index2,
+following the semantics of the corresponding Lua operator
+(that is, it may call metamethods).
+Otherwise returns 0.
+Also returns 0 if any of the indices is not valid.
+
+
+
+The value of op must be one of the following constants:
+
+
+Concatenates the n values at the top of the stack,
+pops them, and leaves the result at the top.
+If n is 1, the result is the single value on the stack
+(that is, the function does nothing);
+if n is 0, the result is the empty string.
+Concatenation is performed following the usual semantics of Lua
+(see §3.4.6).
+
+
+
+
+
+
void lua_copy (lua_State *L, int fromidx, int toidx);
+
+
+Copies the element at index fromidx
+into the valid index toidx,
+replacing the value at that position.
+Values at other positions are not affected.
+
+
+
+
+
+
void lua_createtable (lua_State *L, int narr, int nrec);
+
+
+Creates a new empty table and pushes it onto the stack.
+Parameter narr is a hint for how many elements the table
+will have as a sequence;
+parameter nrec is a hint for how many other elements
+the table will have.
+Lua may use these hints to preallocate memory for the new table.
+This pre-allocation is useful for performance when you know in advance
+how many elements the table will have.
+Otherwise you can use the function lua_newtable.
+
+
+
+
+
+
int lua_dump (lua_State *L,
+ lua_Writer writer,
+ void *data,
+ int strip);
+
+
+Dumps a function as a binary chunk.
+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,
+lua_dump calls function writer (see lua_Writer)
+with the given data
+to write them.
+
+
+
+If strip is true,
+the binary representation is created without debug information
+about the function.
+
+
+
+The value returned is the error code returned by the last
+call to the writer;
+0 means no errors.
+
+
+
+This function does not pop the Lua function from the stack.
+
+
+
+
+
+
+Generates a Lua error,
+using the value at the top of the stack as the error object.
+This function does a long jump,
+and therefore never returns
+(see luaL_error).
+
+
+
+
+
+
+This function performs several tasks,
+according to the value of the parameter what:
+
+
+
+
LUA_GCSTOP:
+stops the garbage collector.
+
+
+
LUA_GCRESTART:
+restarts the garbage collector.
+
+
+
LUA_GCCOLLECT:
+performs a full garbage-collection cycle.
+
+
+
LUA_GCCOUNT:
+returns the current amount of memory (in Kbytes) in use by Lua.
+
+
+
LUA_GCCOUNTB:
+returns the remainder of dividing the current amount of bytes of
+memory in use by Lua by 1024.
+
+
+
LUA_GCSTEP:
+performs an incremental step of garbage collection.
+
+
+
LUA_GCSETPAUSE:
+sets data as the new value
+for the pause of the collector (see §2.5)
+and returns the previous value of the pause.
+
+
+
LUA_GCSETSTEPMUL:
+sets data as the new value for the step multiplier of
+the collector (see §2.5)
+and returns the previous value of the step multiplier.
+
+
+
LUA_GCISRUNNING:
+returns a boolean that tells whether the collector is running
+(i.e., not stopped).
+
+
+
+
+
+For more details about these options,
+see collectgarbage.
+
+
+
+
+
+
+Returns the memory-allocation function of a given state.
+If ud is not NULL, Lua stores in *ud the
+opaque pointer given when the memory-allocator function was set.
+
+
+
+
+
+
int lua_getfield (lua_State *L, int index, const char *k);
+
+
+Pushes onto the stack the value t[k],
+where t is the value at the given index.
+As in Lua, this function may trigger a metamethod
+for the "index" event (see §2.4).
+
+
+
+Returns the type of the pushed value.
+
+
+
+
+
+
+Returns a pointer to a raw memory area associated with the
+given Lua state.
+The application can use this area for any purpose;
+Lua does not use it for anything.
+
+
+
+Each new thread has this area initialized with a copy
+of the area of the main thread.
+
+
+
+By default, this area has the size of a pointer to void,
+but you can recompile Lua with a different size for this area.
+(See LUA_EXTRASPACE in luaconf.h.)
+
+
+
+
+
+
int lua_geti (lua_State *L, int index, lua_Integer i);
+
+
+Pushes onto the stack the value t[i],
+where t is the value at the given index.
+As in Lua, this function may trigger a metamethod
+for the "index" event (see §2.4).
+
+
+
+Returns the type of the pushed value.
+
+
+
+
+
+
+If the value at the given index has a metatable,
+the function pushes that metatable onto the stack and returns 1.
+Otherwise,
+the function returns 0 and pushes nothing on the stack.
+
+
+
+
+
+
+Pushes onto the stack the value t[k],
+where t is the value at the given index
+and k is the value at the top of the stack.
+
+
+
+This function pops the key from the stack,
+pushing the resulting value in its place.
+As in Lua, this function may trigger a metamethod
+for the "index" event (see §2.4).
+
+
+
+Returns the type of the pushed value.
+
+
+
+
+
+
+Returns the index of the top element in the stack.
+Because indices start at 1,
+this result is equal to the number of elements in the stack;
+in particular, 0 means an empty stack.
+
+
+
+
+
+
+Moves the top element into the given valid index,
+shifting up the elements above this index to open space.
+This function cannot be called with a pseudo-index,
+because a pseudo-index is not an actual stack position.
+
+
+
+
+
+
+By default this type is long long,
+(usually a 64-bit two-complement integer),
+but that can be changed to long or int
+(usually a 32-bit two-complement integer).
+(See LUA_INT in luaconf.h.)
+
+
+
+Lua also defines the constants
+LUA_MININTEGER and LUA_MAXINTEGER,
+with the minimum and the maximum values that fit in this type.
+
+
+
+
+
+
+Returns 1 if the value at the given index is an integer
+(that is, the value is a number and is represented as an integer),
+and 0 otherwise.
+
+
+
+
+
+
+The type for continuation-function contexts.
+It must be a numerical type.
+This type is defined as intptr_t
+when intptr_t is available,
+so that it can store pointers too.
+Otherwise, it is defined as ptrdiff_t.
+
+
+
+
+
+
+Returns the length of the value at the given index.
+It is equivalent to the '#' operator in Lua (see §3.4.7) and
+may trigger a metamethod for the "length" event (see §2.4).
+The result is pushed on the stack.
+
+
+
+
+
+
+Loads a Lua chunk without running it.
+If there are no errors,
+lua_load pushes the compiled chunk as a Lua
+function on top of the stack.
+Otherwise, it pushes an error message.
+
+
+
LUA_ERRGCMM:
+error while running a __gc metamethod.
+(This error has no relation with the chunk being loaded.
+It is generated by the garbage collector.)
+
+
+
+
+
+The lua_load function uses a user-supplied reader function
+to read the chunk (see lua_Reader).
+The data argument is an opaque value passed to the reader function.
+
+
+
+The chunkname argument gives a name to the chunk,
+which is used for error messages and in debug information (see §4.9).
+
+
+
+lua_load automatically detects whether the chunk is text or binary
+and loads it accordingly (see program luac).
+The string mode works as in function load,
+with the addition that
+a NULL value is equivalent to the string "bt".
+
+
+
+lua_load uses the stack internally,
+so the reader function must always leave the stack
+unmodified when returning.
+
+
+
+If the resulting function has upvalues,
+its first upvalue is set to the value of the global environment
+stored at index LUA_RIDX_GLOBALS in the registry (see §4.5).
+When loading main chunks,
+this upvalue will be the _ENV variable (see §2.2).
+Other upvalues are initialized with nil.
+
+
+
+
+
+
+Creates a new thread running in a new, independent state.
+Returns NULL if it cannot create the thread or the state
+(due to lack of memory).
+The argument f is the allocator function;
+Lua does all memory allocation for this state through this function.
+The second argument, ud, is an opaque pointer that Lua
+passes to the allocator in every call.
+
+
+
+
+
+
+Creates a new thread, pushes it on the stack,
+and returns a pointer to a lua_State that represents this new thread.
+The new thread returned by this function shares with the original thread
+its global environment,
+but has an independent execution stack.
+
+
+
+There is no explicit function to close or to destroy a thread.
+Threads are subject to garbage collection,
+like any Lua object.
+
+
+
+
+
+
+This function allocates a new block of memory with the given size,
+pushes onto the stack a new full userdata with the block address,
+and returns this address.
+The host program can freely use this memory.
+
+
+
+
+
+
+Pops a key from the stack,
+and pushes a key–value pair from the table at the given index
+(the "next" pair after the given key).
+If there are no more elements in the table,
+then lua_next returns 0 (and pushes nothing).
+
+
+
+A typical traversal looks like this:
+
+
+ /* table is in the stack at index 't' */
+ lua_pushnil(L); /* first key */
+ while (lua_next(L, t) != 0) {
+ /* uses 'key' (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)));
+ /* removes 'value'; keeps 'key' for next iteration */
+ lua_pop(L, 1);
+ }
+
+
+
+While traversing a table,
+do not call lua_tolstring directly on a key,
+unless you know that the key is actually a string.
+Recall that lua_tolstring may change
+the value at the given index;
+this confuses the next call to lua_next.
+
+
+
+See function next for the caveats of modifying
+the table during its traversal.
+
+
+
+
+
+
int lua_numbertointeger (lua_Number n, lua_Integer *p);
+
+
+Converts a Lua float to a Lua integer.
+This macro assumes that n has an integral value.
+If that value is within the range of Lua integers,
+it is converted to an integer and assigned to *p.
+The macro results in a boolean indicating whether the
+conversion was successful.
+(Note that this range test can be tricky to do
+correctly without this macro,
+due to roundings.)
+
+
+
+This macro may evaluate its arguments more than once.
+
+
+
+
+
+
int lua_pcall (lua_State *L, int nargs, int nresults, int msgh);
+
+
+Calls a function in protected mode.
+
+
+
+Both nargs and nresults have the same meaning as
+in lua_call.
+If there are no errors during the call,
+lua_pcall behaves exactly like lua_call.
+However, if there is any error,
+lua_pcall catches it,
+pushes a single value on the stack (the error message),
+and returns an error code.
+Like lua_call,
+lua_pcall always removes the function
+and its arguments from the stack.
+
+
+
+If msgh is 0,
+then the error message returned on the stack
+is exactly the original error message.
+Otherwise, msgh is the stack index of a
+message handler.
+(In the current implementation, this index cannot be a pseudo-index.)
+In case of runtime errors,
+this function will be called with the error message
+and its return value will be the message
+returned on the stack by lua_pcall.
+
+
+
+Typically, the message handler 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 lua_pcall,
+since by then the stack has unwound.
+
+
+
+The lua_pcall function returns one of the following constants
+(defined in lua.h):
+
+
void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n);
+
+
+Pushes a new C closure onto the stack.
+
+
+
+When a C function is created,
+it is possible to associate some values with it,
+thus creating a C closure (see §4.4);
+these values are then accessible to the function whenever it is called.
+To associate values with a C function,
+first these values must be pushed onto the stack
+(when there are multiple values, the first value is pushed first).
+Then lua_pushcclosure
+is called to create and push the C function onto the stack,
+with the argument n telling how many values will be
+associated with the function.
+lua_pushcclosure also pops these values from the stack.
+
+
+
+The maximum value for n is 255.
+
+
+
+When n is zero,
+this function creates a light C function,
+which is just a pointer to the C function.
+In that case, it never raises a memory error.
+
+
+
+
+
+
+Pushes a C function onto the stack.
+This function receives a pointer to a C function
+and pushes onto the stack a Lua value of type function that,
+when called, invokes the corresponding C function.
+
+
+
+Any function to be registered in Lua must
+follow the correct protocol to receive its parameters
+and return its results (see lua_CFunction).
+
+
+
+Pushes onto the stack a formatted string
+and returns a pointer to this string.
+It is similar to the ISO C function sprintf,
+but has some important differences:
+
+
+
+
+You do not have to allocate space for the result:
+the result is a Lua string and Lua takes care of memory allocation
+(and deallocation, through garbage collection).
+
+
+
+The conversion specifiers are quite restricted.
+There are no flags, widths, or precisions.
+The conversion specifiers can only be
+'%%' (inserts the character '%'),
+'%s' (inserts a zero-terminated string, with no size restrictions),
+'%f' (inserts a lua_Number),
+'%L' (inserts a lua_Integer),
+'%p' (inserts a pointer as a hexadecimal numeral),
+'%d' (inserts an int),
+'%c' (inserts an int as a one-byte character), and
+'%U' (inserts a long int as a UTF-8 byte sequence).
+
+Userdata represent C values in Lua.
+A light userdata represents a pointer, a void*.
+It is a value (like a number):
+you do not create it, it has no individual metatable,
+and it is not collected (as it was never created).
+A light userdata is equal to "any"
+light userdata with the same C address.
+
+
+
+
+
+
+This macro is equivalent to lua_pushlstring,
+but can be used only when s is a literal string.
+It automatically provides the string length.
+
+
+
+
+
+
+Pushes the string pointed to by s with size len
+onto the stack.
+Lua makes (or reuses) an internal copy of the given string,
+so the memory at s can be freed or reused immediately after
+the function returns.
+The string can contain any binary data,
+including embedded zeros.
+
+
+
+Returns a pointer to the internal copy of the string.
+
+
+
+
+
+
+Pushes the zero-terminated string pointed to by s
+onto the stack.
+Lua makes (or reuses) an internal copy of the given string,
+so the memory at s can be freed or reused immediately after
+the function returns.
+
+
+
+Returns a pointer to the internal copy of the string.
+
+
+
+If s is NULL, pushes nil and returns NULL.
+
+
+
+
+
+
int lua_rawequal (lua_State *L, int index1, int index2);
+
+
+Returns 1 if the two values in indices index1 and
+index2 are primitively equal
+(that is, without calling metamethods).
+Otherwise returns 0.
+Also returns 0 if any of the indices are not valid.
+
+
+
+
+
+
int lua_rawgetp (lua_State *L, int index, const void *p);
+
+
+Pushes onto the stack the value t[k],
+where t is the table at the given index and
+k is the pointer p represented as a light userdata.
+The access is raw;
+that is, it does not invoke metamethods.
+
+
+
+Returns the type of the pushed value.
+
+
+
+
+
+
+Returns the raw "length" of the value at the given index:
+for strings, this is the string length;
+for tables, this is the result of the length operator ('#')
+with no metamethods;
+for userdata, this is the size of the block of memory allocated
+for the userdata;
+for other values, it is 0.
+
+
+
+
+
+
void lua_rawsetp (lua_State *L, int index, const void *p);
+
+
+Does the equivalent of t[k] = v,
+where t is the table at the given index,
+k is the pointer p represented as a light userdata,
+and v is the value at the top of the stack.
+
+
+
+This function pops the value from the stack.
+The assignment is raw;
+that is, it does not invoke metamethods.
+
+
+
+
+
+
+The reader function used by lua_load.
+Every time it needs another piece of the chunk,
+lua_load calls the reader,
+passing along its data parameter.
+The reader must return a pointer to a block of memory
+with a new piece of the chunk
+and set size to the block size.
+The block must exist until the reader function is called again.
+To signal the end of the chunk,
+the reader must return NULL or set size to zero.
+The reader function may return pieces of any size greater than zero.
+
+
+
+
+
+
+Removes the element at the given valid index,
+shifting down the elements above this index to fill the gap.
+This function cannot be called with a pseudo-index,
+because a pseudo-index is not an actual stack position.
+
+
+
+
+
+
+Moves the top element into the given valid index
+without shifting any element
+(therefore replacing the value at the given index),
+and then pops the top element.
+
+
+
+
+
+
int lua_resume (lua_State *L, lua_State *from, int nargs);
+
+
+Starts and resumes a coroutine in a given thread.
+
+
+
+To start a coroutine,
+you push onto the thread stack the main function plus any arguments;
+then you call lua_resume,
+with nargs 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 lua_yield,
+or all values returned by the body function.
+lua_resume returns
+LUA_YIELD if the coroutine yields,
+LUA_OK if the coroutine finishes its execution
+without errors,
+or an error code in case of errors (see lua_pcall).
+
+
+
+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 resume a coroutine,
+you remove any results from the last lua_yield,
+put on its stack only the values to
+be passed as results from yield,
+and then call lua_resume.
+
+
+
+The parameter from represents the coroutine that is resuming L.
+If there is no such coroutine,
+this parameter can be NULL.
+
+
+
+
+
+
+Rotates the stack elements from idx to the top n positions
+in the direction of the top, for a positive n,
+or -n positions in the direction of the bottom,
+for a negative n.
+The absolute value of n must not be greater than the size
+of the slice being rotated.
+
+
+
+
+
+
+Does the equivalent to t[k] = v,
+where t is the value at the given index,
+v is the value at the top of the stack,
+and k is the value just below the top.
+
+
+
+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 §2.4).
+
+
+
+
+
+
+Accepts any index, or 0,
+and sets the stack top to this index.
+If the new top is larger than the old one,
+then the new elements are filled with nil.
+If index is 0, then all stack elements are removed.
+
+
+
+
+
+
+An opaque structure that points to a thread and indirectly
+(through the thread) to the whole state of a Lua interpreter.
+The Lua library is fully reentrant:
+it has no global variables.
+All information about a state is accessible through this structure.
+
+
+
+A pointer to this structure must be passed as the first argument to
+every function in the library, except to lua_newstate,
+which creates a Lua state from scratch.
+
+
+
+
+
+
+The status can be 0 (LUA_OK) for a normal thread,
+an error code if the thread finished the execution
+of a lua_resume with an error,
+or LUA_YIELD if the thread is suspended.
+
+
+
+You can only call functions in threads with status LUA_OK.
+You can resume threads with status LUA_OK
+(to start a new coroutine) or LUA_YIELD
+(to resume a coroutine).
+
+
+
+
+
+
+Converts the zero-terminated string s to a number,
+pushes that number into the stack,
+and returns the total size of the string,
+that is, its length plus one.
+The conversion can result in an integer or a float,
+according to the lexical conventions of Lua (see §3.1).
+The string may have leading and trailing spaces and a sign.
+If the string is not a valid numeral,
+returns 0 and pushes nothing.
+(Note that the result can be used as a boolean,
+true if the conversion succeeds.)
+
+
+
+
+
+
+Converts the Lua value at the given index to a C boolean
+value (0 or 1).
+Like all tests in Lua,
+lua_toboolean returns true for any Lua value
+different from false and nil;
+otherwise it returns false.
+(If you want to accept only actual boolean values,
+use lua_isboolean to test the value's type.)
+
+
+
+
+
+
lua_Integer lua_tointegerx (lua_State *L, int index, int *isnum);
+
+
+Converts the Lua value at the given index
+to the signed integral type lua_Integer.
+The Lua value must be an integer,
+or a number or string convertible to an integer (see §3.4.3);
+otherwise, lua_tointegerx returns 0.
+
+
+
+If isnum is not NULL,
+its referent is assigned a boolean value that
+indicates whether the operation succeeded.
+
+
+
+
+
+
const char *lua_tolstring (lua_State *L, int index, size_t *len);
+
+
+Converts the Lua value at the given index to a C string.
+If len is not NULL,
+it also sets *len with the string length.
+The Lua value must be a string or a number;
+otherwise, the function returns NULL.
+If the value is a number,
+then lua_tolstring also
+changes the actual value in the stack to a string.
+(This change confuses lua_next
+when lua_tolstring is applied to keys during a table traversal.)
+
+
+
+lua_tolstring returns a fully aligned pointer
+to a string inside the Lua state.
+This string always has a zero ('\0')
+after its last character (as in C),
+but can contain other zeros in its body.
+
+
+
+Because Lua has garbage collection,
+there is no guarantee that the pointer returned by lua_tolstring
+will be valid after the corresponding Lua value is removed from the stack.
+
+
+
+
+
+
lua_Number lua_tonumberx (lua_State *L, int index, int *isnum);
+
+
+Converts the Lua value at the given index
+to the C type lua_Number (see lua_Number).
+The Lua value must be a number or a string convertible to a number
+(see §3.4.3);
+otherwise, lua_tonumberx returns 0.
+
+
+
+If isnum is not NULL,
+its referent is assigned a boolean value that
+indicates whether the operation succeeded.
+
+
+
+
+
+
const void *lua_topointer (lua_State *L, int index);
+
+
+Converts the value at the given index to a generic
+C pointer (void*).
+The value can be a userdata, a table, a thread, or a function;
+otherwise, lua_topointer returns NULL.
+Different objects will give different pointers.
+There is no way to convert the pointer back to its original value.
+
+
+
+Typically this function is used only for debug information.
+
+
+
+
+
+
lua_State *lua_tothread (lua_State *L, int index);
+
+
+Converts the value at the given index to a Lua thread
+(represented as lua_State*).
+This value must be a thread;
+otherwise, the function returns NULL.
+
+
+
+
+
+
+If the value at the given index is a full userdata,
+returns its block address.
+If the value is a light userdata,
+returns its pointer.
+Otherwise, returns NULL.
+
+
+
+
+
+
+Returns the address of the version number stored in the Lua core.
+When called with a valid lua_State,
+returns the address of the version used to create that state.
+When called with NULL,
+returns the address of the version running the call.
+
+
+
+
+
+
+The type of the writer function used by lua_dump.
+Every time it produces another piece of chunk,
+lua_dump calls the writer,
+passing along the buffer to be written (p),
+its size (sz),
+and the data parameter supplied to lua_dump.
+
+
+
+The writer returns an error code:
+0 means no errors;
+any other value means an error and stops lua_dump from
+calling the writer again.
+
+
+
+
+
+
+This function is equivalent to lua_yieldk,
+but it has no continuation (see §4.7).
+Therefore, when the thread resumes,
+it continues the function that called
+the function calling lua_yield.
+
+
+
+
+
+
int lua_yieldk (lua_State *L,
+ int nresults,
+ lua_KContext ctx,
+ lua_KFunction k);
+
+
+Yields a coroutine (thread).
+
+
+
+When a C function calls lua_yieldk,
+the running coroutine suspends its execution,
+and the call to lua_resume that started this coroutine returns.
+The parameter nresults is the number of values from the stack
+that will be passed as results to lua_resume.
+
+
+
+When the coroutine is resumed again,
+Lua calls the given continuation function k to continue
+the execution of the C function that yielded (see §4.7).
+This continuation function receives the same stack
+from the previous function,
+with the n results removed and
+replaced by the arguments passed to lua_resume.
+Moreover,
+the continuation function receives the value ctx
+that was passed to lua_yieldk.
+
+
+
+Usually, this function does not return;
+when the coroutine eventually resumes,
+it continues executing the continuation function.
+However, there is one special case,
+which is when this function is called
+from inside a line hook (see §4.9).
+In that case, lua_yieldk should be called with no continuation
+(probably in the form of lua_yield),
+and the hook should return immediately after the call.
+Lua will yield and,
+when the coroutine resumes again,
+it will continue the normal execution
+of the (Lua) function that triggered the hook.
+
+
+
+This function can raise an error if it is called from a thread
+with a pending C call with no continuation function,
+or it is called from a thread that is not running inside a resume
+(e.g., the main thread).
+
+
+
+
+
+
+
+
+Lua has no built-in debugging facilities.
+Instead, it offers a special interface
+by means of functions and hooks.
+This interface allows the construction of different
+kinds of debuggers, profilers, and other tools
+that need "inside information" from the interpreter.
+
+
+
+
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 linedefined; /* (S) */
+ int lastlinedefined; /* (S) */
+ unsigned char nups; /* (u) number of upvalues */
+ unsigned char nparams; /* (u) number of parameters */
+ char isvararg; /* (u) */
+ char istailcall; /* (t) */
+ char short_src[LUA_IDSIZE]; /* (S) */
+ /* private part */
+ other fields
+} lua_Debug;
+
+
+A structure used to carry different pieces of
+information about a function or an activation record.
+lua_getstack fills only the private part
+of this structure, for later use.
+To fill the other fields of lua_Debug with useful information,
+call lua_getinfo.
+
+
+
+The fields of lua_Debug have the following meaning:
+
+
+
+
source:
+the name of the chunk that created the function.
+If source starts with a '@',
+it means that the function was defined in a file where
+the file name follows the '@'.
+If source starts with a '=',
+the remainder of its contents describe the source in a user-dependent manner.
+Otherwise,
+the function was defined in a string where
+source is that string.
+
+
+
short_src:
+a "printable" version of source, to be used in error messages.
+
+
+
linedefined:
+the line number where the definition of the function starts.
+
+
+
lastlinedefined:
+the line number where the definition of the function ends.
+
+
+
what:
+the string "Lua" if the function is a Lua function,
+"C" if it is a C function,
+"main" if it is the main part of a chunk.
+
+
+
currentline:
+the current line where the given function is executing.
+When no line information is available,
+currentline is set to -1.
+
+
+
name:
+a reasonable name for the given function.
+Because functions in Lua are first-class values,
+they do not have a fixed name:
+some functions can be the value of multiple global variables,
+while others can be stored only in a table field.
+The lua_getinfo function checks how the function was
+called to find a suitable name.
+If it cannot find a name,
+then name is set to NULL.
+
+
+
namewhat:
+explains the name field.
+The value of namewhat can be
+"global", "local", "method",
+"field", "upvalue", or "" (the empty string),
+according to how the function was called.
+(Lua uses the empty string when no other option seems to apply.)
+
+
+
istailcall:
+true if this function invocation was called by a tail call.
+In this case, the caller of this level is not in the stack.
+
+
+
nups:
+the number of upvalues of the function.
+
+
+
nparams:
+the number of fixed parameters of the function
+(always 0 for C functions).
+
+
+
isvararg:
+true if the function is a vararg function
+(always true for C functions).
+
int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar);
+
+
+Gets information about a specific function or function invocation.
+
+
+
+To get information about a function invocation,
+the parameter ar must be a valid activation record that was
+filled by a previous call to lua_getstack or
+given as argument to a hook (see lua_Hook).
+
+
+
+To get information about a function you push it onto the stack
+and start the what string with the character '>'.
+(In that case,
+lua_getinfo pops the function from the top of the stack.)
+For instance, to know in which line a function f was defined,
+you can write the following code:
+
+
+ lua_Debug ar;
+ lua_getglobal(L, "f"); /* get global 'f' */
+ lua_getinfo(L, ">S", &ar);
+ printf("%d\n", ar.linedefined);
+
+
+
+Each character in the string what
+selects some fields of the structure ar to be filled or
+a value to be pushed on the stack:
+
+
+
+
'n': fills in the field name and namewhat;
+
+
+
'S':
+fills in the fields source, short_src,
+linedefined, lastlinedefined, and what;
+
+
+
'l': fills in the field currentline;
+
+
+
't': fills in the field istailcall;
+
+
+
'u': fills in the fields
+nups, nparams, and isvararg;
+
+
+
'f':
+pushes onto the stack the function that is
+running at the given level;
+
+
+
'L':
+pushes onto the stack a table whose indices are the
+numbers of the lines that are valid on the function.
+(A valid line is a line with some associated code,
+that is, a line where you can put a break point.
+Non-valid lines include empty lines and comments.)
+
+
+
+If this option is given together with option 'f',
+its table is pushed after the function.
+
+
+
+
+
+This function returns 0 on error
+(for instance, an invalid option in what).
+
+
+
+
+
+
const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n);
+
+
+Gets information about a local variable of
+a given activation record or a given function.
+
+
+
+In the first case,
+the parameter ar must be a valid activation record that was
+filled by a previous call to lua_getstack or
+given as argument to a hook (see lua_Hook).
+The index n selects which local variable to inspect;
+see debug.getlocal for details about variable indices
+and names.
+
+
+
+lua_getlocal pushes the variable's value onto the stack
+and returns its name.
+
+
+
+In the second case, ar must be NULL and the function
+to be inspected must be at the top of the stack.
+In this case, only parameters of Lua functions are visible
+(as there is no information about what variables are active)
+and no values are pushed onto the stack.
+
+
+
+Returns NULL (and pushes nothing)
+when the index is greater than
+the number of active local variables.
+
+
+
+
+
+
int lua_getstack (lua_State *L, int level, lua_Debug *ar);
+
+
+Gets information about the interpreter runtime stack.
+
+
+
+This function fills parts of a lua_Debug structure with
+an identification of the activation record
+of the function executing at a given level.
+Level 0 is the current running function,
+whereas level n+1 is the function that has called level n
+(except for tail calls, which do not count on the stack).
+When there are no errors, lua_getstack returns 1;
+when called with a level greater than the stack depth,
+it returns 0.
+
+
+
+
+
+
const char *lua_getupvalue (lua_State *L, int funcindex, int n);
+
+
+Gets information about a closure's upvalue.
+(For Lua functions,
+upvalues are the external local variables that the function uses,
+and that are consequently included in its closure.)
+lua_getupvalue gets the index n of an upvalue,
+pushes the upvalue's value onto the stack,
+and returns its name.
+funcindex points to the closure in the stack.
+(Upvalues have no particular order,
+as they are active through the whole function.
+So, they are numbered in an arbitrary order.)
+
+
+
+Returns NULL (and pushes nothing)
+when the index is greater than the number of upvalues.
+For C functions, this function uses the empty string ""
+as a name for all upvalues.
+
+
+
+
+
+
+Whenever a hook is called, its ar argument has its field
+event set to the specific event that triggered the hook.
+Lua identifies these events with the following constants:
+LUA_HOOKCALL, LUA_HOOKRET,
+LUA_HOOKTAILCALL, LUA_HOOKLINE,
+and LUA_HOOKCOUNT.
+Moreover, for line events, the field currentline is also set.
+To get the value of any other field in ar,
+the hook must call lua_getinfo.
+
+
+
+For call events, event can be LUA_HOOKCALL,
+the normal value, or LUA_HOOKTAILCALL, for a tail call;
+in this case, there will be no corresponding return event.
+
+
+
+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,
+this execution occurs without any calls to hooks.
+
+
+
+Hook functions cannot have continuations,
+that is, they cannot call lua_yieldk,
+lua_pcallk, or lua_callk with a non-null k.
+
+
+
+Hook functions can yield under the following conditions:
+Only count and line events can yield
+and they cannot yield any value;
+to yield a hook function must finish its execution
+calling lua_yield with nresults equal to zero.
+
+
+
+
+
+
void lua_sethook (lua_State *L, lua_Hook f, int mask, int count);
+
+
+Sets the debugging hook function.
+
+
+
+Argument f is the hook function.
+mask specifies on which events the hook will be called:
+it is formed by a bitwise or of the constants
+LUA_MASKCALL,
+LUA_MASKRET,
+LUA_MASKLINE,
+and LUA_MASKCOUNT.
+The count argument is only meaningful when the mask
+includes LUA_MASKCOUNT.
+For each event, the hook is called as explained below:
+
+
+
+
The call hook: is called when the interpreter calls a function.
+The hook is called just after Lua enters the new function,
+before the function gets its arguments.
+
+
+
The return hook: is called when the interpreter returns from a function.
+The hook is called just before Lua leaves the function.
+There is no standard way to access the values
+to be returned by the function.
+
+
+
The line hook: 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.)
+
+
+
The count hook: is called after the interpreter executes every
+count instructions.
+(This event only happens while Lua is executing a Lua function.)
+
+
+
+
+
+A hook is disabled by setting mask to zero.
+
+
+
+
+
+
const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n);
+
+
+Sets the value of a local variable of a given activation record.
+Parameters ar and n are as in lua_getlocal
+(see lua_getlocal).
+lua_setlocal assigns the value at the top of the stack
+to the variable and returns its name.
+It also pops the value from the stack.
+
+
+
+Returns NULL (and pops nothing)
+when the index is greater than
+the number of active local variables.
+
+
+
+
+
+
const char *lua_setupvalue (lua_State *L, int funcindex, int n);
+
+
+Sets the value of a closure's upvalue.
+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.
+Parameters funcindex and n are as in the lua_getupvalue
+(see lua_getupvalue).
+
+
+
+Returns NULL (and pops nothing)
+when the index is greater than the number of upvalues.
+
+
+
+
+
+
void *lua_upvalueid (lua_State *L, int funcindex, int n);
+
+
+Returns a unique identifier for the upvalue numbered n
+from the closure at index funcindex.
+Parameters funcindex and n are as in the lua_getupvalue
+(see lua_getupvalue)
+(but n cannot be greater than the number of upvalues).
+
+
+
+These unique identifiers allow a program to check whether different
+closures share upvalues.
+Lua closures that share an upvalue
+(that is, that access a same external local variable)
+will return identical ids for those upvalue indices.
+
+
+
+
+
+
+
+The auxiliary library 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.
+
+
+
+All functions and types from the auxiliary library
+are defined in header file lauxlib.h and
+have a prefix luaL_.
+
+
+
+All functions in the auxiliary library are built on
+top of the basic API,
+and so they provide nothing that cannot be done with that API.
+Nevertheless, the use of the auxiliary library ensures
+more consistency to your code.
+
+
+
+Several functions in the auxiliary library use internally some
+extra stack slots.
+When a function in the auxiliary library uses less than five slots,
+it does not check the stack size;
+it simply assumes that there are enough slots.
+
+
+
+Several functions in the auxiliary library are used to
+check C function arguments.
+Because the error message is formatted for arguments
+(e.g., "bad argument #1"),
+you should not use these functions for other stack values.
+
+
+
+Functions called luaL_check*
+always raise an error if the check is not satisfied.
+
+
+
+
+Adds the value at the top of the stack
+to the buffer B
+(see luaL_Buffer).
+Pops the value.
+
+
+
+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.
+
+
+
+
+
+
int luaL_argerror (lua_State *L, int arg, const char *extramsg);
+
+
+Raises an error reporting a problem with argument arg
+of the C function that called it,
+using a standard message
+that includes extramsg as a comment:
+
+
Then initialize it and preallocate a space of
+size sz with a call luaL_buffinitsize(L, &b, sz).
+
+
Then copy the string into that space.
+
+
+Finish by calling luaL_pushresultsize(&b, sz),
+where sz is the total size of the resulting string
+copied into that space.
+
+
+
+
+
+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
+the top of the stack is.
+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 luaL_addvalue.)
+After calling luaL_pushresult the stack is back to its
+level when the buffer was initialized,
+plus the final string on its top.
+
+
+
+
+
+
int luaL_callmeta (lua_State *L, int obj, const char *e);
+
+
+Calls a metamethod.
+
+
+
+If the object at index obj has a metatable and this
+metatable has a field e,
+this function calls this field passing the object as its only argument.
+In this case this function returns true and pushes onto the
+stack the value returned by the call.
+If there is no metatable or no metamethod,
+this function returns false (without pushing any value on the stack).
+
+
+
+
+
+
lua_Integer luaL_checkinteger (lua_State *L, int arg);
+
+
+Checks whether the function argument arg is an integer
+(or can be converted to an integer)
+and returns this integer cast to a lua_Integer.
+
+
+
+
+
+
int luaL_checkoption (lua_State *L,
+ int arg,
+ const char *def,
+ const char *const lst[]);
+
+
+Checks whether the function argument arg is a string and
+searches for this string in the array lst
+(which must be NULL-terminated).
+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.
+
+
+
+If def is not NULL,
+the function uses def as a default value when
+there is no argument arg or when this argument is nil.
+
+
+
+This is a useful function for mapping strings to C enums.
+(The usual convention in Lua libraries is
+to use strings instead of numbers to select options.)
+
+
+
+
+
+
void luaL_checkstack (lua_State *L, int sz, const char *msg);
+
+
+Grows the stack size to top + sz elements,
+raising an error if the stack cannot grow to that size.
+msg is an additional text to go into the error message
+(or NULL for no additional text).
+
+
+
+
+
+
void *luaL_checkudata (lua_State *L, int arg, const char *tname);
+
+
+Checks whether the function argument arg is a userdata
+of the type tname (see luaL_newmetatable) and
+returns the userdata address (see lua_touserdata).
+
+
+
+
+
+
+Checks whether the core running the call,
+the core that created the Lua state,
+and the code making the call are all using the same version of Lua.
+Also checks whether the core running the call
+and the core that created the Lua state
+are using the same address space.
+
+
+
+
+
+
int luaL_error (lua_State *L, const char *fmt, ...);
+
+
+Raises an error.
+The error message format is given by fmt
+plus any extra arguments,
+following the same rules of lua_pushfstring.
+It also adds at the beginning of the message the file name and
+the line number where the error occurred,
+if this information is available.
+
+
+
+This function never returns,
+but it is an idiom to use it in C functions
+as return luaL_error(args).
+
+
+
+
+
+
int luaL_getmetafield (lua_State *L, int obj, const char *e);
+
+
+Pushes onto the stack the field e from the metatable
+of the object at index obj and returns the type of pushed value.
+If the object does not have a metatable,
+or if the metatable does not have this field,
+pushes nothing and returns LUA_TNIL.
+
+
+
+
+
+
int luaL_getmetatable (lua_State *L, const char *tname);
+
+
+Pushes onto the stack the metatable associated with name tname
+in the registry (see luaL_newmetatable).
+If there is no metatable associated with tname,
+returns false and pushes nil.
+
+
+
+
+
+
int luaL_getsubtable (lua_State *L, int idx, const char *fname);
+
+
+Ensures that the value t[fname],
+where t is the value at index idx,
+is a table,
+and pushes that table onto the stack.
+Returns true if it finds a previous table there
+and false if it creates a new table.
+
+
+
+
+
+
+Creates a copy of string s by replacing
+any occurrence of the string p
+with the string r.
+Pushes the resulting string on the stack and returns it.
+
+
+
+
+
+
+Returns the "length" of the value at the given index
+as a number;
+it is equivalent to the '#' operator in Lua (see §3.4.7).
+Raises an error if the result of the operation is not an integer.
+(This case only can happen through metamethods.)
+
+
+
+
+
+
+Loads a buffer as a Lua chunk.
+This function uses lua_load to load the chunk in the
+buffer pointed to by buff with size sz.
+
+
+
+This function returns the same results as lua_load.
+name is the chunk name,
+used for debug information and error messages.
+The string mode works as in function lua_load.
+
+
+
+
+
+
+Loads a file as a Lua chunk.
+This function uses lua_load to load the chunk in the file
+named filename.
+If filename is NULL,
+then it loads from the standard input.
+The first line in the file is ignored if it starts with a #.
+
+
+
+The string mode works as in function lua_load.
+
+
+
+This function returns the same results as lua_load,
+but it has an extra error code LUA_ERRFILE
+if it cannot open/read the file or the file has a wrong mode.
+
+
+
+As lua_load, this function only loads the chunk;
+it does not run it.
+
+
+
+
+
+
+Creates a new table with a size optimized
+to store all entries in the array l
+(but does not actually store them).
+It is intended to be used in conjunction with luaL_setfuncs
+(see luaL_newlib).
+
+
+
+It is implemented as a macro.
+The array l must be the actual array,
+not a pointer to it.
+
+
+
+
+
+
int luaL_newmetatable (lua_State *L, const char *tname);
+
+
+If the registry already has the key tname,
+returns 0.
+Otherwise,
+creates a new table to be used as a metatable for userdata,
+adds to this new table the pair __name = tname,
+adds to the registry the pair [tname] = new table,
+and returns 1.
+(The entry __name is used by some error-reporting functions.)
+
+
+
+In both cases pushes onto the stack the final value associated
+with tname in the registry.
+
+
+
+
+
+
+Creates a new Lua state.
+It calls lua_newstate with an
+allocator based on the standard C realloc function
+and then sets a panic function (see §4.6) that prints
+an error message to the standard error output in case of fatal
+errors.
+
+
+
+Returns the new state,
+or NULL if there is a memory allocation error.
+
+
+
+
+
+
lua_Integer luaL_optinteger (lua_State *L,
+ int arg,
+ lua_Integer d);
+
+
+If the function argument arg is an integer
+(or convertible to an integer),
+returns this integer.
+If this argument is absent or is nil,
+returns d.
+Otherwise, raises an error.
+
+
+
+
+
+
lua_Number luaL_optnumber (lua_State *L, int arg, lua_Number d);
+
+
+If the function argument arg is a number,
+returns this number.
+If this argument is absent or is nil,
+returns d.
+Otherwise, raises an error.
+
+
+
+
+
+
+If the function argument arg is a string,
+returns this string.
+If this argument is absent or is nil,
+returns d.
+Otherwise, raises an error.
+
+
+
+
+
+
+Returns an address to a space of size sz
+where you can copy a string to be added to buffer B
+(see luaL_Buffer).
+After copying the string into this space you must call
+luaL_addsize with the size of the string to actually add
+it to the buffer.
+
+
+
+
+
+
+Creates and returns a reference,
+in the table at index t,
+for the object at the top of the stack (and pops the object).
+
+
+
+A reference is a unique integer key.
+As long as you do not manually add integer keys into table t,
+luaL_ref ensures the uniqueness of the key it returns.
+You can retrieve an object referred by reference r
+by calling lua_rawgeti(L, t, r).
+Function luaL_unref frees a reference and its associated object.
+
+
+
+If the object at the top of the stack is nil,
+luaL_ref returns the constant LUA_REFNIL.
+The constant LUA_NOREF is guaranteed to be different
+from any reference returned by luaL_ref.
+
+
+
+
+
+
+Type for arrays of functions to be registered by
+luaL_setfuncs.
+name is the function name and func is a pointer to
+the function.
+Any array of luaL_Reg must end with a sentinel entry
+in which both name and func are NULL.
+
+
+
+
+
+
+If modname is not already present in package.loaded,
+calls function openf with string modname as an argument
+and sets the call result in package.loaded[modname],
+as if that function has been called through require.
+
+
+
+If glb is true,
+also stores the module into global modname.
+
+
+
+Leaves a copy of the module on the stack.
+
+
+
+
+
+
void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup);
+
+
+Registers all functions in the array l
+(see luaL_Reg) into the table on the top of the stack
+(below optional upvalues, see next).
+
+
+
+When nup is not zero,
+all functions are created sharing nup upvalues,
+which must be previously pushed on the stack
+on top of the library table.
+These values are popped from the stack after the registration.
+
+
+
+
+
+
+Sets the metatable of the object at the top of the stack
+as the metatable associated with name tname
+in the registry (see luaL_newmetatable).
+
+
+
+
+
+
+The standard representation for file handles,
+which is used by the standard I/O library.
+
+
+
+A file handle is implemented as a full userdata,
+with a metatable called LUA_FILEHANDLE
+(where LUA_FILEHANDLE is a macro with the actual metatable's name).
+The metatable is created by the I/O library
+(see luaL_newmetatable).
+
+
+
+This userdata must start with the structure luaL_Stream;
+it can contain other data after this initial structure.
+Field f points to the corresponding C stream
+(or it can be NULL to indicate an incompletely created handle).
+Field closef points to a Lua function
+that will be called to close the stream
+when the handle is closed or collected;
+this function receives the file handle as its sole argument and
+must return either true (in case of success)
+or nil plus an error message (in case of error).
+Once Lua calls this field,
+the field value is changed to NULL
+to signal that the handle is closed.
+
+
+
+
+
+
const char *luaL_tolstring (lua_State *L, int idx, size_t *len);
+
+
+Converts any Lua value at the given index to a C string
+in a reasonable format.
+The resulting string is pushed onto the stack and also
+returned by the function.
+If len is not NULL,
+the function also sets *len with the string length.
+
+
+
+If the value has a metatable with a "__tostring" field,
+then luaL_tolstring calls the corresponding metamethod
+with the value as argument,
+and uses the result of the call as its result.
+
+
+
+
+
+
+Creates and pushes a traceback of the stack L1.
+If msg is not NULL it is appended
+at the beginning of the traceback.
+The level parameter tells at which level
+to start the traceback.
+
+
+
+
+
+
+Releases reference ref from the table at index t
+(see luaL_ref).
+The entry is removed from the table,
+so that the referred object can be collected.
+The reference ref is also freed to be used again.
+
+
+
+Pushes onto the stack a string identifying the current position
+of the control at level lvl in the call stack.
+Typically this string has the following format:
+
+
+ chunkname:currentline:
+
+Level 0 is the running function,
+level 1 is the function that called the running function,
+etc.
+
+
+
+This function is used to build a prefix for error messages.
+
+
+
+
+
+
+
+
+The standard Lua libraries provide useful functions
+that are implemented directly through the C API.
+Some of these functions provide essential services to the language
+(e.g., type and getmetatable);
+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 requirements that
+deserve an implementation in C (e.g., table.sort).
+
+
+
+All libraries are implemented through the official C API
+and are provided as separate C modules.
+Currently, Lua has the following standard libraries:
+
+
+Except for the basic and the package libraries,
+each library provides all its functions as fields of a global table
+or as methods of its objects.
+
+
+
+To have access to these libraries,
+the C host program should call the luaL_openlibs function,
+which opens all standard libraries.
+Alternatively,
+the host program can open them individually by using
+luaL_requiref to call
+luaopen_base (for the basic library),
+luaopen_package (for the package library),
+luaopen_coroutine (for the coroutine library),
+luaopen_string (for the string library),
+luaopen_utf8 (for the UTF8 library),
+luaopen_table (for the table library),
+luaopen_math (for the mathematical library),
+luaopen_io (for the I/O library),
+luaopen_os (for the operating system library),
+and luaopen_debug (for the debug library).
+These functions are declared in lualib.h.
+
+
+
+
+The basic library provides core functions to Lua.
+If you do not include this library in your application,
+you should check carefully whether you need to provide
+implementations for some of its facilities.
+
+
+
+Calls error if
+the value of its argument v is false (i.e., nil or false);
+otherwise, returns all its arguments.
+In case of error,
+message is the error object;
+when absent, it defaults to "assertion failed!"
+
+
+
+
+
+This function is a generic interface to the garbage collector.
+It performs different functions according to its first argument, opt:
+
+
+
+
"collect":
+performs a full garbage-collection cycle.
+This is the default option.
+
+
+
"stop":
+stops automatic execution of the garbage collector.
+The collector will run only when explicitly invoked,
+until a call to restart it.
+
+
+
"restart":
+restarts automatic execution of the garbage collector.
+
+
+
"count":
+returns the total memory in use by Lua in Kbytes.
+The value has a fractional part,
+so that it multiplied by 1024
+gives the exact number of bytes in use by Lua
+(except for overflows).
+
+
+
"step":
+performs a garbage-collection step.
+The step "size" is controlled by arg.
+With a zero value,
+the collector will perform one basic (indivisible) step.
+For non-zero values,
+the collector will perform as if that amount of memory
+(in KBytes) had been allocated by Lua.
+Returns true if the step finished a collection cycle.
+
+
+
"setpause":
+sets arg as the new value for the pause of
+the collector (see §2.5).
+Returns the previous value for pause.
+
+
+
"setstepmul":
+sets arg as the new value for the step multiplier of
+the collector (see §2.5).
+Returns the previous value for step.
+
+
+
"isrunning":
+returns a boolean that tells whether the collector is running
+(i.e., not stopped).
+
+Opens the named file and executes its contents as a Lua chunk.
+When called without arguments,
+dofile executes the contents of the standard input (stdin).
+Returns all values returned by the chunk.
+In case of errors, dofile propagates the error
+to its caller (that is, dofile does not run in protected mode).
+
+
+
+
+
+Terminates the last protected function called
+and returns message as the error object.
+Function error never returns.
+
+
+
+Usually, error adds some information about the error position
+at the beginning of the message, if the message is a string.
+The level argument specifies how to get the error position.
+With level 1 (the default), the error position is where the
+error function was called.
+Level 2 points the error to where the function
+that called error was called; and so on.
+Passing a level 0 avoids the addition of error position information
+to the message.
+
+
+
+
+
+A global variable (not a function) that
+holds the global environment (see §2.2).
+Lua itself does not use this variable;
+changing its value does not affect any environment,
+nor vice versa.
+
+
+
+
+
+If object does not have a metatable, returns nil.
+Otherwise,
+if the object's metatable has a "__metatable" field,
+returns the associated value.
+Otherwise, returns the metatable of the given object.
+
+
+
+
+
+If chunk is a string, the chunk is this string.
+If chunk is a function,
+load calls it repeatedly to get the chunk pieces.
+Each call to chunk must return a string that concatenates
+with previous results.
+A return of an empty string, nil, or no value signals the end of the chunk.
+
+
+
+If there are no syntactic errors,
+returns the compiled chunk as a function;
+otherwise, returns nil plus the error message.
+
+
+
+If the resulting function has upvalues,
+the first upvalue is set to the value of env,
+if that parameter is given,
+or to the value of the global environment.
+Other upvalues are initialized with nil.
+(When you load a main chunk,
+the resulting function will always have exactly one upvalue,
+the _ENV variable (see §2.2).
+However,
+when you load a binary chunk created from a function (see string.dump),
+the resulting function can have an arbitrary number of upvalues.)
+All upvalues are fresh, that is,
+they are not shared with any other function.
+
+
+
+chunkname is used as the name of the chunk for error messages
+and debug information (see §4.9).
+When absent,
+it defaults to chunk, if chunk is a string,
+or to "=(load)" otherwise.
+
+
+
+The string mode controls whether the chunk can be text or binary
+(that is, a precompiled chunk).
+It may be the string "b" (only binary chunks),
+"t" (only text chunks),
+or "bt" (both binary and text).
+The default is "bt".
+
+
+
+Lua does not check the consistency of binary chunks.
+Maliciously crafted binary chunks can crash
+the interpreter.
+
+
+
+
+
+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.
+next returns the next index of the table
+and its associated value.
+When called with nil as its second argument,
+next returns an initial index
+and its associated value.
+When called with the last index,
+or with nil in an empty table,
+next returns nil.
+If the second argument is absent, then it is interpreted as nil.
+In particular,
+you can use next(t) to check whether a table is empty.
+
+
+
+The order in which the indices are enumerated is not specified,
+even for numeric indices.
+(To traverse a table in numeric order,
+use a numerical for.)
+
+
+
+The behavior of next is undefined if,
+during the traversal,
+you assign any value to a non-existent field in the table.
+You may however modify existing fields.
+In particular, you may clear existing fields.
+
+
+
+
+
+Calls function f with
+the given arguments in protected mode.
+This means that any error inside f is not propagated;
+instead, pcall 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, pcall also returns all results from the call,
+after this first result.
+In case of any error, pcall returns false plus the error message.
+
+
+
+
+
+Receives any number of arguments
+and prints their values to stdout,
+using the tostring function to convert each argument to a string.
+print is not intended for formatted output,
+but only as a quick way to show a value,
+for instance for debugging.
+For complete control over the output,
+use string.format and io.write.
+
+
+
+
+
+Sets the real value of table[index] to value,
+without invoking any metamethod.
+table must be a table,
+index any value different from nil and NaN,
+and value any Lua value.
+
+
+
+If index is a number,
+returns all arguments after argument number index;
+a negative number indexes from the end (-1 is the last argument).
+Otherwise, index must be the string "#",
+and select returns the total number of extra arguments it received.
+
+
+
+
+
+Sets the metatable for the given table.
+(You cannot change the metatable of other types from Lua, only from C.)
+If metatable is nil,
+removes the metatable of the given table.
+If the original metatable has a "__metatable" field,
+raises an error.
+
+
+
+When called with no base,
+tonumber tries to convert its argument to a number.
+If the argument is already a number or
+a string convertible to a number,
+then tonumber returns this number;
+otherwise, it returns nil.
+
+
+
+The conversion of strings can result in integers or floats,
+according to the lexical conventions of Lua (see §3.1).
+(The string may have leading and trailing spaces and a sign.)
+
+
+
+When called with base,
+then e must be a string to be interpreted as
+an integer numeral in that base.
+The base may be any integer between 2 and 36, inclusive.
+In bases above 10, the letter 'A' (in either upper or lower case)
+represents 10, 'B' represents 11, and so forth,
+with 'Z' representing 35.
+If the string e is not a valid numeral in the given base,
+the function returns nil.
+
+
+
+
+
+Receives a value of any type and
+converts it to a string in a human-readable format.
+Floats always produce strings with some
+floating-point indication (either a decimal dot or an exponent).
+(For complete control of how numbers are converted,
+use string.format.)
+
+
+
+If the metatable of v has a "__tostring" field,
+then tostring calls the corresponding value
+with v as argument,
+and uses the result of the call as its result.
+
+
+
+
+
+Returns the type of its only argument, coded as a string.
+The possible results of this function are
+"nil" (a string, not the value nil),
+"number",
+"string",
+"boolean",
+"table",
+"function",
+"thread",
+and "userdata".
+
+
+
+
+
+A global variable (not a function) that
+holds a string containing the current interpreter version.
+The current value of this variable is "Lua 5.3".
+
+
+
+
+
+The operations related to coroutines comprise a sub-library of
+the basic library and come inside the table coroutine.
+See §2.6 for a general description of coroutines.
+
+
+
+Starts or continues the execution of coroutine co.
+The first time you resume a coroutine,
+it starts running its body.
+The values val1, ... are passed
+as the arguments to the body function.
+If the coroutine has yielded,
+resume restarts it;
+the values val1, ... are passed
+as the results from the yield.
+
+
+
+If the coroutine runs without any errors,
+resume returns true plus any values passed to yield
+(when the coroutine yields) or any values returned by the body function
+(when the coroutine terminates).
+If there is any error,
+resume returns false plus the error message.
+
+
+
+
+
+Returns the status of coroutine co, as a string:
+"running",
+if the coroutine is running (that is, it called status);
+"suspended", if the coroutine is suspended in a call to yield,
+or if it has not started running yet;
+"normal" if the coroutine is active but not running
+(that is, it has resumed another coroutine);
+and "dead" if the coroutine has finished its body function,
+or if it has stopped with an error.
+
+
+
+
+
+Creates a new coroutine, with body f.
+f 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 resume.
+Returns the same values returned by resume,
+except the first boolean.
+In case of error, propagates the error.
+
+
+
+
+
+The package library provides basic
+facilities for loading modules in Lua.
+It exports one function directly in the global environment:
+require.
+Everything else is exported in a table package.
+
+
+
+Loads the given module.
+The function starts by looking into the package.loaded table
+to determine whether modname is already loaded.
+If it is, then require returns the value stored
+at package.loaded[modname].
+Otherwise, it tries to find a loader for the module.
+
+
+
+To find a loader,
+require is guided by the package.searchers sequence.
+By changing this sequence,
+we can change how require looks for a module.
+The following explanation is based on the default configuration
+for package.searchers.
+
+
+
+First require queries package.preload[modname].
+If it has a value,
+this value (which must be a function) is the loader.
+Otherwise require searches for a Lua loader using the
+path stored in package.path.
+If that also fails, it searches for a C loader using the
+path stored in package.cpath.
+If that also fails,
+it tries an all-in-one loader (see package.searchers).
+
+
+
+Once a loader is found,
+require calls the loader with two arguments:
+modname and an extra value dependent on how it got the loader.
+(If the loader came from a file,
+this extra value is the file name.)
+If the loader returns any non-nil value,
+require assigns the returned value to package.loaded[modname].
+If the loader does not return a non-nil value and
+has not assigned any value to package.loaded[modname],
+then require assigns true to this entry.
+In any case, require returns the
+final value of package.loaded[modname].
+
+
+
+If there is any error loading or running the module,
+or if it cannot find any loader for the module,
+then require raises an error.
+
+
+
+
+
+The path used by require to search for a C loader.
+
+
+
+Lua initializes the C path package.cpath in the same way
+it initializes the Lua path package.path,
+using the environment variable LUA_CPATH_5_3
+or the environment variable LUA_CPATH
+or a default path defined in luaconf.h.
+
+
+
+
+
+A table used by require to control which
+modules are already loaded.
+When you require a module modname and
+package.loaded[modname] is not false,
+require simply returns the value stored there.
+
+
+
+This variable is only a reference to the real table;
+assignments to this variable do not change the
+table used by require.
+
+
+
+
+
+Dynamically links the host program with the C library libname.
+
+
+
+If funcname is "*",
+then it only links with the library,
+making the symbols exported by the library
+available to other dynamically linked libraries.
+Otherwise,
+it looks for a function funcname inside the library
+and returns this function as a C function.
+So, funcname must follow the lua_CFunction prototype
+(see lua_CFunction).
+
+
+
+This is a low-level function.
+It completely bypasses the package and module system.
+Unlike require,
+it does not perform any path searching and
+does not automatically adds extensions.
+libname must be the complete file name of the C library,
+including if necessary a path and an extension.
+funcname must be the exact name exported by the C library
+(which may depend on the C compiler and linker used).
+
+
+
+This function is not supported by Standard C.
+As such, it is only available on some platforms
+(Windows, Linux, Mac OS X, Solaris, BSD,
+plus other Unix systems that support the dlfcn standard).
+
+
+
+
+
+The path used by require to search for a Lua loader.
+
+
+
+At start-up, Lua initializes this variable with
+the value of the environment variable LUA_PATH_5_3 or
+the environment variable LUA_PATH or
+with a default path defined in luaconf.h,
+if those environment variables are not defined.
+Any ";;" in the value of the environment variable
+is replaced by the default path.
+
+
+
+
+
+A table used by require to control how to load modules.
+
+
+
+Each entry in this table is a searcher function.
+When looking for a module,
+require calls each of these searchers in ascending order,
+with the module name (the argument given to require) as its
+sole parameter.
+The function can return another function (the module loader)
+plus an extra value that will be passed to that loader,
+or a string explaining why it did not find that module
+(or nil if it has nothing to say).
+
+
+
+Lua initializes this table with four searcher functions.
+
+
+
+The first searcher simply looks for a loader in the
+package.preload table.
+
+
+
+The second searcher looks for a loader as a Lua library,
+using the path stored at package.path.
+The search is done as described in function package.searchpath.
+
+
+
+The third searcher looks for a loader as a C library,
+using the path given by the variable package.cpath.
+Again,
+the search is done as described in function package.searchpath.
+For instance,
+if the C path is the string
+
+
+ "./?.so;./?.dll;/usr/local/?/init.so"
+
+the searcher for module foo
+will try to open the files ./foo.so, ./foo.dll,
+and /usr/local/foo/init.so, in that order.
+Once it finds a C library,
+this searcher first uses a dynamic link facility to link the
+application with the library.
+Then it tries to find a C function inside the library to
+be used as the loader.
+The name of this C function is the string "luaopen_"
+concatenated with a copy of the module name where each dot
+is replaced by an underscore.
+Moreover, if the module name has a hyphen,
+its suffix after (and including) the first hyphen is removed.
+For instance, if the module name is a.b.c-v2.1,
+the function name will be luaopen_a_b_c.
+
+
+
+The fourth searcher tries an all-in-one loader.
+It searches the C path for a library for
+the root name of the given module.
+For instance, when requiring a.b.c,
+it will search for a C library for a.
+If found, it looks into it for an open function for
+the submodule;
+in our example, that would be luaopen_a_b_c.
+With this facility, a package can pack several C submodules
+into one single library,
+with each submodule keeping its original open function.
+
+
+
+All searchers except the first one (preload) return as the extra value
+the file name where the module was found,
+as returned by package.searchpath.
+The first searcher returns no extra value.
+
+
+
+
+
+Searches for the given name in the given path.
+
+
+
+A path is a string containing a sequence of
+templates separated by semicolons.
+For each template,
+the function replaces each interrogation mark (if any)
+in the template with a copy of name
+wherein all occurrences of sep
+(a dot, by default)
+were replaced by rep
+(the system's directory separator, by default),
+and then tries to open the resulting file name.
+
+
+
+For instance, if the path is the string
+
+
+ "./?.lua;./?.lc;/usr/local/?/init.lua"
+
+the search for the name foo.a
+will try to open the files
+./foo/a.lua, ./foo/a.lc, and
+/usr/local/foo/a/init.lua, in that order.
+
+
+
+Returns the resulting name of the first file that it can
+open in read mode (after closing the file),
+or nil plus an error message if none succeeds.
+(This error message lists all file names it tried to open.)
+
+
+
+
+
+
+
+
+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 -1, and so on.
+
+
+
+The string library provides all its functions inside the table
+string.
+It also sets a metatable for strings
+where the __index field points to the string table.
+Therefore, you can use the string functions in object-oriented style.
+For instance, string.byte(s,i)
+can be written as s:byte(i).
+
+
+
+The string library assumes one-byte character encodings.
+
+
+
+Returns the internal numerical codes of the characters s[i],
+s[i+1], ..., s[j].
+The default value for i is 1;
+the default value for j is i.
+These indices are corrected
+following the same rules of function string.sub.
+
+
+
+Numerical codes are not necessarily portable across platforms.
+
+
+
+
+
+Receives zero 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 corresponding argument.
+
+
+
+Numerical codes are not necessarily portable across platforms.
+
+
+
+
+
+Returns a string containing a binary representation
+(a binary chunk)
+of the given function,
+so that a later load on this string returns
+a copy of the function (but with new upvalues).
+If strip is a true value,
+the binary representation is created without debug information
+about the function
+(local variable names, lines, etc.).
+
+
+
+Functions with upvalues have only their number of upvalues saved.
+When (re)loaded,
+those upvalues receive fresh instances containing nil.
+(You can use the debug library to serialize
+and reload the upvalues of a function
+in a way adequate to your needs.)
+
+
+
+
+
+Looks for the first match of
+pattern (see §6.4.1) in the string s.
+If it finds a match, then find returns the indices of s
+where this occurrence starts and ends;
+otherwise, it returns nil.
+A third, optional numerical argument init specifies
+where to start the search;
+its default value is 1 and can be negative.
+A value of true as a fourth, optional argument plain
+turns off the pattern matching facilities,
+so the function does a plain "find substring" operation,
+with no characters in pattern being considered magic.
+Note that if plain is given, then init must be given as well.
+
+
+
+If the pattern has captures,
+then in a successful match
+the captured values are also returned,
+after the two indices.
+
+
+
+
+
+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 ISO C function sprintf.
+The only differences are that the options/modifiers
+*, h, L, l, n,
+and p are not supported
+and that there is an extra option, q.
+The q option formats a string between double quotes,
+using escape sequences when necessary to ensure that
+it can safely be read back by the Lua interpreter.
+For instance, the call
+
+
+ string.format('%q', 'a string with "quotes" and \n new line')
+
+may produce the string:
+
+
+ "a string with \"quotes\" and \
+ new line"
+
+
+
+Options
+A and a (when available),
+E, e, f,
+G, and g all expect a number as argument.
+Options c, d,
+i, o, u, X, and x
+expect an integer.
+Option q expects a string;
+option s expects a string without embedded zeros.
+If the argument to option s is not a string,
+it is converted to one following the same rules of tostring.
+
+
+
+
+
+Returns an iterator function that,
+each time it is called,
+returns the next captures from pattern (see §6.4.1)
+over the string s.
+If pattern specifies no captures,
+then the whole match is produced in each call.
+
+
+
+As an example, the following loop
+will iterate over all the words from string s,
+printing one per line:
+
+
+ s = "hello world from Lua"
+ for w in string.gmatch(s, "%a+") do
+ print(w)
+ end
+
+The next example collects all pairs key=value from the
+given string into a table:
+
+
+ t = {}
+ s = "from=world, to=Lua"
+ for k, v in string.gmatch(s, "(%w+)=(%w+)") do
+ t[k] = v
+ end
+
+
+
+For this function, a caret '^' at the start of a pattern does not
+work as an anchor, as this would prevent the iteration.
+
+
+
+
+
+Returns a copy of s
+in which all (or the first n, if given)
+occurrences of the pattern (see §6.4.1) have been
+replaced by a replacement string specified by repl,
+which can be a string, a table, or a function.
+gsub also returns, as its second value,
+the total number of matches that occurred.
+The name gsub comes from Global SUBstitution.
+
+
+
+If repl is a string, then its value is used for replacement.
+The character % works as an escape character:
+any sequence in repl of the form %d,
+with d between 1 and 9,
+stands for the value of the d-th captured substring.
+The sequence %0 stands for the whole match.
+The sequence %% stands for a single %.
+
+
+
+If repl is a table, then the table is queried for every match,
+using the first capture as the key.
+
+
+
+If repl is a function, then this function is called every time a
+match occurs, with all captured substrings passed as arguments,
+in order.
+
+
+
+In any case,
+if the pattern specifies no captures,
+then it behaves as if the whole pattern was inside a capture.
+
+
+
+If the value returned by the table query or by the function call
+is a string or a number,
+then it is used as the replacement string;
+otherwise, if it is false or nil,
+then there is no replacement
+(that is, the original match is kept in the string).
+
+
+
+Here are some examples:
+
+
+ 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 load(s)()
+ end)
+ --> x="4+5 = 9"
+
+ local t = {name="lua", version="5.3"}
+ x = string.gsub("$name-$version.tar.gz", "%$(%w+)", t)
+ --> x="lua-5.3.tar.gz"
+
+Receives a string and returns a copy of this string with all
+uppercase letters changed to lowercase.
+All other characters are left unchanged.
+The definition of what an uppercase letter is depends on the current locale.
+
+
+
+
+
+Looks for the first match of
+pattern (see §6.4.1) in the string s.
+If it finds one, then match returns
+the captures from the pattern;
+otherwise it returns nil.
+If pattern specifies no captures,
+then the whole match is returned.
+A third, optional numerical argument init specifies
+where to start the search;
+its default value is 1 and can be negative.
+
+
+
+
+
+Returns a binary string containing the values v1, v2, etc.
+packed (that is, serialized in binary form)
+according to the format string fmt (see §6.4.2).
+
+
+
+
+
+Returns the size of a string resulting from string.pack
+with the given format.
+The format string cannot have the variable-length options
+'s' or 'z' (see §6.4.2).
+
+
+
+
+
+Returns a string that is the concatenation of n copies of
+the string s separated by the string sep.
+The default value for sep is the empty string
+(that is, no separator).
+Returns the empty string if n is not positive.
+
+
+
+
+
+Returns the substring of s that
+starts at i and continues until j;
+i and j can be negative.
+If j is absent, then it is assumed to be equal to -1
+(which is the same as the string length).
+In particular,
+the call string.sub(s,1,j) returns a prefix of s
+with length j,
+and string.sub(s, -i) returns a suffix of s
+with length i.
+
+
+
+If, after the translation of negative indices,
+i is less than 1,
+it is corrected to 1.
+If j is greater than the string length,
+it is corrected to that length.
+If, after these corrections,
+i is greater than j,
+the function returns the empty string.
+
+
+
+
+
+Returns the values packed in string s (see string.pack)
+according to the format string fmt (see §6.4.2).
+An optional pos marks where
+to start reading in s (default is 1).
+After the read values,
+this function also returns the index of the first unread byte in s.
+
+
+
+
+
+Receives a string and returns a copy of this string with all
+lowercase letters changed to uppercase.
+All other characters are left unchanged.
+The definition of what a lowercase letter is depends on the current locale.
+
+
+
+
+
+
+Patterns in Lua are described by regular strings,
+which are interpreted as patterns by the pattern-matching functions
+string.find,
+string.gmatch,
+string.gsub,
+and string.match.
+This section describes the syntax and the meaning
+(that is, what they match) of these strings.
+
+
+
+
Character Class:
+A character class is used to represent a set of characters.
+The following combinations are allowed in describing a character class:
+
+
+
+
x:
+(where x is not one of the magic characters
+^$()%.[]*+-?)
+represents the character x itself.
+
+
+
.: (a dot) represents all characters.
+
+
%a: represents all letters.
+
+
%c: represents all control characters.
+
+
%d: represents all digits.
+
+
%g: represents all printable characters except space.
+
+
%l: represents all lowercase letters.
+
+
%p: represents all punctuation characters.
+
+
%s: represents all space characters.
+
+
%u: represents all uppercase letters.
+
+
%w: represents all alphanumeric characters.
+
+
%x: represents all hexadecimal digits.
+
+
%x: (where x is any non-alphanumeric character)
+represents the character x.
+This is the standard way to escape the magic characters.
+Any non-alphanumeric character
+(including all punctuations, even the non-magical)
+can be preceded by a '%'
+when used to represent itself in a pattern.
+
+
+
[set]:
+represents the class which is the union of all
+characters in set.
+A range of characters can be specified by
+separating the end characters of the range,
+in ascending order, with a '-'.
+All classes %x described above can also be used as
+components in set.
+All other characters in set represent themselves.
+For example, [%w_] (or [_%w])
+represents all alphanumeric characters plus the underscore,
+[0-7] represents the octal digits,
+and [0-7%l%-] represents the octal digits plus
+the lowercase letters plus the '-' character.
+
+
+
+The interaction between ranges and classes is not defined.
+Therefore, patterns like [%a-z] or [a-%%]
+have no meaning.
+
+
+
[^set]:
+represents the complement of set,
+where set is interpreted as above.
+
+
+
+For all classes represented by single letters (%a, %c, etc.),
+the corresponding uppercase letter represents the complement of the class.
+For instance, %S represents all non-space characters.
+
+
+
+The definitions of letter, space, and other character groups
+depend on the current locale.
+In particular, the class [a-z] may not be equivalent to %l.
+
+
+
+
+
+
Pattern Item:
+A pattern item can be
+
+
+
+
+a single character class,
+which matches any single character in the class;
+
+
+
+a single character class followed by '*',
+which matches zero or more repetitions of characters in the class.
+These repetition items will always match the longest possible sequence;
+
+
+
+a single character class followed by '+',
+which matches one or more repetitions of characters in the class.
+These repetition items will always match the longest possible sequence;
+
+
+
+a single character class followed by '-',
+which also matches zero or more repetitions of characters in the class.
+Unlike '*',
+these repetition items will always match the shortest possible sequence;
+
+
+
+a single character class followed by '?',
+which matches zero or one occurrence of a character in the class.
+It always matches one occurrence if possible;
+
+
+
+%n, for n between 1 and 9;
+such item matches a substring equal to the n-th captured string
+(see below);
+
+
+
+%bxy, where x and y are two distinct characters;
+such item matches strings that start with x, end with y,
+and where the x and y are balanced.
+This means that, if one reads the string from left to right,
+counting +1 for an x and -1 for a y,
+the ending y is the first y where the count reaches 0.
+For instance, the item %b() matches expressions with
+balanced parentheses.
+
+
+
+%f[set], a frontier pattern;
+such item matches an empty string at any position such that
+the next character belongs to set
+and the previous character does not belong to set.
+The set set is interpreted as previously described.
+The beginning and the end of the subject are handled as if
+they were the character '\0'.
+
+
+
+
+
+
+
+
Pattern:
+A pattern is a sequence of pattern items.
+A caret '^' at the beginning of a pattern anchors the match at the
+beginning of the subject string.
+A '$' at the end of a pattern anchors the match at the
+end of the subject string.
+At other positions,
+'^' and '$' have no special meaning and represent themselves.
+
+
+
+
+
+
Captures:
+A pattern can contain sub-patterns enclosed in parentheses;
+they describe captures.
+When a match succeeds, the substrings of the subject string
+that match captures are stored (captured) for future use.
+Captures are numbered according to their left parentheses.
+For instance, in the pattern "(a*(.)%w(%s*))",
+the part of the string matching "a*(.)%w(%s*)" is
+stored as the first capture (and therefore has number 1);
+the character matching "." is captured with number 2,
+and the part matching "%s*" has number 3.
+
+
+
+As a special case, the empty capture () captures
+the current string position (a number).
+For instance, if we apply the pattern "()aa()" on the
+string "flaaap", there will be two captures: 3 and 5.
+
+
+
+
+
+
+
+
+The first argument to string.pack,
+string.packsize, and string.unpack
+is a format string,
+which describes the layout of the structure being created or read.
+
+
+
+A format string is a sequence of conversion options.
+The conversion options are as follows:
+
+
+
<: sets little endian
+
>: sets big endian
+
=: sets native endian
+
![n]: sets maximum alignment to n
+(default is native alignment)
+
b: a signed byte (char)
+
B: an unsigned byte (char)
+
h: a signed short (native size)
+
H: an unsigned short (native size)
+
l: a signed long (native size)
+
L: an unsigned long (native size)
+
j: a lua_Integer
+
J: a lua_Unsigned
+
T: a size_t (native size)
+
i[n]: a signed int with n bytes
+(default is native size)
+
I[n]: an unsigned int with n bytes
+(default is native size)
+
f: a float (native size)
+
d: a double (native size)
+
n: a lua_Number
+
cn: a fixed-sized string with n bytes
+
z: a zero-terminated string
+
s[n]: a string preceded by its length
+coded as an unsigned integer with n bytes
+(default is a size_t)
+
x: one byte of padding
+
Xop: an empty item that aligns
+according to option op
+(which is otherwise ignored)
+
'': (empty space) ignored
+
+(A "[n]" means an optional integral numeral.)
+Except for padding, spaces, and configurations
+(options "xX <=>!"),
+each option corresponds to an argument (in string.pack)
+or a result (in string.unpack).
+
+
+
+For options "!n", "sn", "in", and "In",
+n can be any integer between 1 and 16.
+All integral options check overflows;
+string.pack checks whether the given value fits in the given size;
+string.unpack checks whether the read value fits in a Lua integer.
+
+
+
+Any format string starts as if prefixed by "!1=",
+that is,
+with maximum alignment of 1 (no alignment)
+and native endianness.
+
+
+
+Alignment works as follows:
+For each option,
+the format gets extra padding until the data starts
+at an offset that is a multiple of the minimum between the
+option size and the maximum alignment;
+this minimum must be a power of 2.
+Options "c" and "z" are not aligned;
+option "s" follows the alignment of its starting integer.
+
+
+
+All padding is filled with zeros by string.pack
+(and ignored by string.unpack).
+
+
+
+
+
+
+
+
+This library provides basic support for UTF-8 encoding.
+It provides all its functions inside the table utf8.
+This library does not provide any support for Unicode other
+than the handling of the encoding.
+Any operation that needs the meaning of a character,
+such as character classification, is outside its scope.
+
+
+
+Unless stated otherwise,
+all functions that expect a byte position as a parameter
+assume that the given position is either the start of a byte sequence
+or one plus the length of the subject string.
+As in the string library,
+negative indices count from the end of the string.
+
+
+
+Receives zero or more integers,
+converts each one to its corresponding UTF-8 byte sequence
+and returns a string with the concatenation of all these sequences.
+
+
+
+
+
+The pattern (a string, not a function) "[\0-\x7F\xC2-\xF4][\x80-\xBF]*"
+(see §6.4.1),
+which matches exactly one UTF-8 byte sequence,
+assuming that the subject is a valid UTF-8 string.
+
+
+
+
+
+will iterate over all characters in string s,
+with p being the position (in bytes) and c the code point
+of each character.
+It raises an error if it meets any invalid byte sequence.
+
+
+
+
+
+Returns the codepoints (as integers) from all characters in s
+that start between byte position i and j (both included).
+The default for i is 1 and for j is i.
+It raises an error if it meets any invalid byte sequence.
+
+
+
+
+
+Returns the number of UTF-8 characters in string s
+that start between positions i and j (both inclusive).
+The default for i is 1 and for j is -1.
+If it finds any invalid byte sequence,
+returns a false value plus the position of the first invalid byte.
+
+
+
+
+
+Returns the position (in bytes) where the encoding of the
+n-th character of s
+(counting from position i) starts.
+A negative n gets characters before position i.
+The default for i is 1 when n is non-negative
+and #s + 1 otherwise,
+so that utf8.offset(s, -n) gets the offset of the
+n-th character from the end of the string.
+If the specified character is neither in the subject
+nor right after its end,
+the function returns nil.
+
+
+
+As a special case,
+when n is 0 the function returns the start of the encoding
+of the character that contains the i-th byte of s.
+
+
+
+This function assumes that s is a valid UTF-8 string.
+
+
+
+
+
+
+
+
+This library provides generic functions for table manipulation.
+It provides all its functions inside the table table.
+
+
+
+Remember that, whenever an operation needs the length of a table,
+the table must be a proper sequence
+or have a __len metamethod (see §3.4.7).
+All functions ignore non-numeric keys
+in the tables given as arguments.
+
+
+
+Given a list where all elements are strings or numbers,
+returns the string list[i]..sep..list[i+1] ··· sep..list[j].
+The default value for sep is the empty string,
+the default for i is 1,
+and the default for j is #list.
+If i is greater than j, returns the empty string.
+
+
+
+
+
+Inserts element value at position pos in list,
+shifting up the elements
+list[pos], list[pos+1], ···, list[#list].
+The default value for pos is #list+1,
+so that a call table.insert(t,x) inserts x at the end
+of list t.
+
+
+
+
+
+Moves elements from table a1 to table a2.
+This function performs the equivalent to the following
+multiple assignment:
+a2[t],··· = a1[f],···,a1[e].
+The default for a2 is a1.
+The destination range can overlap with the source range.
+Index f must be positive.
+
+
+
+
+
+Returns a new table with all parameters stored into keys 1, 2, etc.
+and with a field "n" with the total number of parameters.
+Note that the resulting table may not be a sequence.
+
+
+
+
+
+Removes from list the element at position pos,
+returning the value of the removed element.
+When pos is an integer between 1 and #list,
+it shifts down the elements
+list[pos+1], list[pos+2], ···, list[#list]
+and erases element list[#list];
+The index pos can also be 0 when #list is 0,
+or #list + 1;
+in those cases, the function erases the element list[pos].
+
+
+
+The default value for pos is #list,
+so that a call table.remove(l) removes the last element
+of list l.
+
+
+
+
+
+Sorts list elements in a given order, in-place,
+from list[1] to list[#list].
+If comp is given,
+then it must be a function that receives two list elements
+and returns true when the first element must come
+before the second in the final order
+(so that not comp(list[i+1],list[i]) will be true after the sort).
+If comp is not given,
+then the standard Lua operator < is used instead.
+
+
+
+The sort algorithm is not stable;
+that is, elements considered equal by the given order
+may have their relative positions changed by the sort.
+
+
+
+
+
+This library provides basic mathematical functions.
+It provides all its functions and constants inside the table math.
+Functions with the annotation "integer/float" give
+integer results for integer arguments
+and float results for float (or mixed) arguments.
+Rounding functions
+(math.ceil, math.floor, and math.modf)
+return an integer when the result fits in the range of an integer,
+or a float otherwise.
+
+
+
+
+Returns the arc tangent of y/x (in radians),
+but uses the signs of both parameters to find the
+quadrant of the result.
+(It also handles correctly the case of x being zero.)
+
+
+
+The default value for x is 1,
+so that the call math.atan(y)
+returns the arc tangent of y.
+
+
+
+
+
+When called without arguments,
+returns a pseudo-random float with uniform distribution
+in the range [0,1).
+When called with two integers m and n,
+math.random returns a pseudo-random integer
+with uniform distribution in the range [m, n].
+(The value m-n cannot be negative and must fit in a Lua integer.)
+The call math.random(n) is equivalent to math.random(1,n).
+
+
+
+This function is an interface to the underling
+pseudo-random generator function provided by C.
+No guarantees can be given for its statistical properties.
+
+
+
+
+
+The I/O library provides two different styles for file manipulation.
+The first one uses implicit file handles;
+that is, there are operations to set a default input file and a
+default output file,
+and all input/output operations are over these default files.
+The second style uses explicit file handles.
+
+
+
+When using implicit file handles,
+all operations are supplied by table io.
+When using explicit file handles,
+the operation io.open returns a file handle
+and then all operations are supplied as methods of the file handle.
+
+
+
+The table io also provides
+three predefined file handles with their usual meanings from C:
+io.stdin, io.stdout, and io.stderr.
+The I/O library never closes these files.
+
+
+
+Unless otherwise stated,
+all I/O functions return nil on failure
+(plus an error message as a second result and
+a system-dependent error code as a third result)
+and some value different from nil on success.
+On non-POSIX systems,
+the computation of the error message and error code
+in case of errors
+may be not thread safe,
+because they rely on the global C variable errno.
+
+
+
+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 this file handle as the default input file.
+When called without parameters,
+it returns the current default input file.
+
+
+
+In case of errors this function raises the error,
+instead of returning an error code.
+
+
+
+
+
+Opens the given file name in read mode
+and returns an iterator function that
+works like file:lines(···) over the opened file.
+When the iterator function detects the end of file,
+it returns no values (to finish the loop) and automatically closes the file.
+
+
+
+The call io.lines() (with no file name) is equivalent
+to io.input():lines("*l");
+that is, it iterates over the lines of the default input file.
+In this case it does not close the file when the loop ends.
+
+
+
+In case of errors this function raises the error,
+instead of returning an error code.
+
+
+
+
+
+This function opens a file,
+in the mode specified in the string mode.
+It returns a new file handle,
+or, in case of errors, nil plus an error message.
+
+
+
+The mode string can be any of the following:
+
+
+
"r": read mode (the default);
+
"w": write mode;
+
"a": append mode;
+
"r+": update mode, all previous data is preserved;
+
"w+": update mode, all previous data is erased;
+
"a+": append update mode, previous data is preserved,
+ writing is only allowed at the end of file.
+
+The mode string can also have a 'b' at the end,
+which is needed in some systems to open the file in binary mode.
+
+
+
+
+
+This function is system dependent and is not available
+on all platforms.
+
+
+
+Starts program prog in a separated process and returns
+a file handle that you can use to read data from this program
+(if mode is "r", the default)
+or to write data to this program
+(if mode is "w").
+
+
+
+
+
+Checks whether obj is a valid file handle.
+Returns the string "file" if obj is an open file handle,
+"closed file" if obj is a closed file handle,
+or nil if obj is not a file handle.
+
+
+
+
+
+Closes file.
+Note that files are automatically closed when
+their handles are garbage collected,
+but that takes an unpredictable amount of time to happen.
+
+
+
+When closing a file handle created with io.popen,
+file:close returns the same values
+returned by os.execute.
+
+
+
+
+
+Returns an iterator function that,
+each time it is called,
+reads the file according to the given formats.
+When no format is given,
+uses "l" as a default.
+As an example, the construction
+
+
+ for c in file:lines(1) do body end
+
+will iterate over all characters of the file,
+starting at the current position.
+Unlike io.lines, this function does not close the file
+when the loop ends.
+
+
+
+In case of errors this function raises the error,
+instead of returning an error code.
+
+
+
+
+
+Reads the file file,
+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 nil if it cannot read data with the specified format.
+(In this latter case,
+the function does not read subsequent formats.)
+When called without formats,
+it uses a default format that reads the next line
+(see below).
+
+
+
+The available formats are
+
+
+
+
"n":
+reads a numeral and returns it as a float or an integer,
+following the lexical conventions of Lua.
+(The numeral may have leading spaces and a sign.)
+This format always reads the longest input sequence that
+is a valid prefix for a number;
+if that prefix does not form a valid number
+(e.g., an empty string, "0x", or "3.4e-"),
+it is discarded and the function returns nil.
+
+
+
"i":
+reads an integral number and returns it as an integer.
+
+
+
"a":
+reads the whole file, starting at the current position.
+On end of file, it returns the empty string.
+
+
+
"l":
+reads the next line skipping the end of line,
+returning nil on end of file.
+This is the default format.
+
+
+
"L":
+reads the next line keeping the end-of-line character (if present),
+returning nil on end of file.
+
+
+
number:
+reads a string with up to this number of bytes,
+returning nil on end of file.
+If number is zero,
+it reads nothing and returns an empty string,
+or nil on end of file.
+
+
+
+The formats "l" and "L" should be used only for text files.
+
+
+
+
+
+Sets and gets the file position,
+measured from the beginning of the file,
+to the position given by offset plus a base
+specified by the string whence, as follows:
+
+
+
"set": base is position 0 (beginning of the file);
+
"cur": base is current position;
+
"end": base is end of file;
+
+In case of success, seek returns the final file position,
+measured in bytes from the beginning of the file.
+If seek fails, it returns nil,
+plus a string describing the error.
+
+
+
+The default value for whence is "cur",
+and for offset is 0.
+Therefore, the call file:seek() returns the current
+file position, without changing it;
+the call file:seek("set") sets the position to the
+beginning of the file (and returns 0);
+and the call file:seek("end") sets the position to the
+end of the file, and returns its size.
+
+
+
+
+
+Returns a string or a table containing date and time,
+formatted according to the given string format.
+
+
+
+If the time argument is present,
+this is the time to be formatted
+(see the os.time function for a description of this value).
+Otherwise, date formats the current time.
+
+
+
+If format starts with '!',
+then the date is formatted in Coordinated Universal Time.
+After this optional character,
+if format is the string "*t",
+then date returns a table with the following fields:
+year (four digits), month (1–12), day (1–31),
+hour (0–23), min (0–59), sec (0–61),
+wday (weekday, Sunday is 1),
+yday (day of the year),
+and isdst (daylight saving flag, a boolean).
+This last field may be absent
+if the information is not available.
+
+
+
+If format is not "*t",
+then date returns the date as a string,
+formatted according to the same rules as the ISO C function strftime.
+
+
+
+When called without arguments,
+date returns a reasonable date and time representation that depends on
+the host system and on the current locale
+(that is, os.date() is equivalent to os.date("%c")).
+
+
+
+On non-POSIX systems,
+this function may be not thread safe
+because of its reliance on C function gmtime and C function localtime.
+
+
+
+
+
+Returns the difference, in seconds,
+from time t1 to time t2
+(where the times are values returned by os.time).
+In POSIX, Windows, and some other systems,
+this value is exactly t2-t1.
+
+
+
+
+
+This function is equivalent to the ISO C function system.
+It passes command to be executed by an operating system shell.
+Its first result is true
+if the command terminated successfully,
+or nil otherwise.
+After this first result
+the function returns a string plus a number,
+as follows:
+
+
+
+
"exit":
+the command terminated normally;
+the following number is the exit status of the command.
+
+
+
"signal":
+the command was terminated by a signal;
+the following number is the signal that terminated the command.
+
+
+
+
+
+When called without a command,
+os.execute returns a boolean that is true if a shell is available.
+
+
+
+
+
+Calls the ISO C function exit to terminate the host program.
+If code is true,
+the returned status is EXIT_SUCCESS;
+if code is false,
+the returned status is EXIT_FAILURE;
+if code is a number,
+the returned status is this number.
+The default value for code is true.
+
+
+
+If the optional second argument close is true,
+closes the Lua state before exiting.
+
+
+
+
+
+Deletes the file (or empty directory, on POSIX systems)
+with the given name.
+If this function fails, it returns nil,
+plus a string describing the error and the error code.
+
+
+
+
+
+Renames file or directory named oldname to newname.
+If this function fails, it returns nil,
+plus a string describing the error and the error code.
+
+
+
+
+
+Sets the current locale of the program.
+locale is a system-dependent string specifying a locale;
+category is an optional string describing which category to change:
+"all", "collate", "ctype",
+"monetary", "numeric", or "time";
+the default category is "all".
+The function returns the name of the new locale,
+or nil if the request cannot be honored.
+
+
+
+If locale is the empty string,
+the current locale is set to an implementation-defined native locale.
+If locale is the string "C",
+the current locale is set to the standard C locale.
+
+
+
+When called with nil as the first argument,
+this function only returns the name of the current locale
+for the given category.
+
+
+
+This function may be not thread safe
+because of its reliance on C function setlocale.
+
+
+
+
+
+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 year, month, and day,
+and may have fields
+hour (default is 12),
+min (default is 0),
+sec (default is 0),
+and isdst (default is nil).
+For a description of these fields, see the os.date function.
+
+
+
+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 time can be used only as an argument to
+os.date and os.difftime.
+
+
+
+
+
+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 explicitly removed when no longer needed.
+
+
+
+On POSIX systems,
+this function also creates a file with that name,
+to avoid security risks.
+(Someone else might create the file with wrong permissions
+in the time between getting the name and creating the file.)
+You still have to open the file to use it
+and to remove it (even if you do not use it).
+
+
+
+When possible,
+you may prefer to use io.tmpfile,
+which automatically removes the file when the program ends.
+
+
+
+
+
+
+
+
+This library provides
+the functionality of the debug interface (§4.9) to Lua programs.
+You should exert care when using this library.
+Several of its functions
+violate basic assumptions about Lua code
+(e.g., that variables local to a function
+cannot be accessed from outside;
+that userdata metatables cannot be changed by Lua code;
+that Lua programs do not crash)
+and therefore can compromise otherwise secure code.
+Moreover, some functions in this library may be slow.
+
+
+
+All functions in this library are provided
+inside the debug table.
+All functions that operate over a thread
+have an optional first argument which is the
+thread to operate over.
+The default is always the current thread.
+
+
+
+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 cont finishes this function,
+so that the caller continues its execution.
+
+
+
+Note that commands for debug.debug are not lexically nested
+within any function and so have no direct access to local variables.
+
+
+
+
+
+Returns the current hook settings of the thread, as three values:
+the current hook function, the current hook mask,
+and the current hook count
+(as set by the debug.sethook 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 f,
+which means the function running at level f of the call stack
+of the given thread:
+level 0 is the current function (getinfo itself);
+level 1 is the function that called getinfo
+(except for tail calls, which do not count on the stack);
+and so on.
+If f is a number larger than the number of active functions,
+then getinfo returns nil.
+
+
+
+The returned table can contain all the fields returned by lua_getinfo,
+with the string what describing which fields to fill in.
+The default for what is to get all information available,
+except the table of valid lines.
+If present,
+the option 'f'
+adds a field named func with the function itself.
+If present,
+the option 'L'
+adds a field named activelines with the table of
+valid lines.
+
+
+
+For instance, the expression debug.getinfo(1,"n").name returns
+a table with a name for the current function,
+if a reasonable name can be found,
+and the expression debug.getinfo(print)
+returns a table with all available information
+about the print function.
+
+
+
+
+
+This function returns the name and the value of the local variable
+with index local of the function at level f of the stack.
+This function accesses not only explicit local variables,
+but also parameters, temporaries, etc.
+
+
+
+The first parameter or local variable has index 1, and so on,
+following the order that they are declared in the code,
+counting only the variables that are active
+in the current scope of the function.
+Negative indices refer to vararg parameters;
+-1 is the first vararg parameter.
+The function returns nil if there is no variable with the given index,
+and raises an error when called with a level out of range.
+(You can call debug.getinfo to check whether the level is valid.)
+
+
+
+Variable names starting with '(' (open parenthesis)
+represent variables with no known names
+(internal variables such as loop control variables,
+and variables from chunks saved without debug information).
+
+
+
+The parameter f may also be a function.
+In that case, getlocal returns only the name of function parameters.
+
+
+
+
+
+This function returns the name and the value of the upvalue
+with index up of the function f.
+The function returns nil if there is no upvalue with the given index.
+
+
+
+Variable names starting with '(' (open parenthesis)
+represent variables with no known names
+(variables from chunks saved without debug information).
+
+
+
+
+
+Sets the given function as a hook.
+The string mask and the number count describe
+when the hook will be called.
+The string mask may have any combination of the following characters,
+with the given meaning:
+
+
+
'c': the hook is called every time Lua calls a function;
+
'r': the hook is called every time Lua returns from a function;
+
'l': the hook is called every time Lua enters a new line of code.
+
+Moreover,
+with a count different from zero,
+the hook is called also after every count instructions.
+
+
+
+When called without arguments,
+debug.sethook turns off the hook.
+
+
+
+When the hook is called, its first parameter is a string
+describing the event that has triggered its call:
+"call" (or "tail call"),
+"return",
+"line", and "count".
+For line events,
+the hook also gets the new line number as its second parameter.
+Inside a hook,
+you can call getinfo with level 2 to get more information about
+the running function
+(level 0 is the getinfo function,
+and level 1 is the hook function).
+
+
+
+
+
+This function assigns the value value to the local variable
+with index local of the function at level level of the stack.
+The function returns nil if there is no local
+variable with the given index,
+and raises an error when called with a level out of range.
+(You can call getinfo to check whether the level is valid.)
+Otherwise, it returns the name of the local variable.
+
+
+
+See debug.getlocal for more information about
+variable indices and names.
+
+
+
+
+
+This function assigns the value value to the upvalue
+with index up of the function f.
+The function returns nil if there is no upvalue
+with the given index.
+Otherwise, it returns the name of the upvalue.
+
+
+
+
+
+If message is present but is neither a string nor nil,
+this function returns message without further processing.
+Otherwise,
+it returns a string with a traceback of the call stack.
+The optional message string is appended
+at the beginning of the traceback.
+An optional level number tells at which level
+to start the traceback
+(default is 1, the function calling traceback).
+
+
+
+
+
+Returns a unique identifier (as a light userdata)
+for the upvalue numbered n
+from the given function.
+
+
+
+These unique identifiers allow a program to check whether different
+closures share upvalues.
+Lua closures that share an upvalue
+(that is, that access a same external local variable)
+will return identical ids for those upvalue indices.
+
+
+
+
+
+Although Lua has been designed as an extension language,
+to be embedded in a host C program,
+it is also frequently used as a standalone language.
+An interpreter for Lua as a standalone language,
+called simply lua,
+is provided with the standard distribution.
+The standalone interpreter includes
+all standard libraries, including the debug library.
+Its usage is:
+
+
+ lua [options] [script [args]]
+
+The options are:
+
+
+
-e stat: executes string stat;
+
-l mod: "requires" mod;
+
-i: enters interactive mode after running script;
+
-v: prints version information;
+
-E: ignores environment variables;
+
--: stops handling options;
+
-: executes stdin as a file and stops handling options.
+
+After handling its options, lua runs the given script.
+When called without arguments,
+lua behaves as lua -v -i
+when the standard input (stdin) is a terminal,
+and as lua - otherwise.
+
+
+
+When called without option -E,
+the interpreter checks for an environment variable LUA_INIT_5_3
+(or LUA_INIT if the versioned name is not defined)
+before running any argument.
+If the variable content has the format @filename,
+then lua executes the file.
+Otherwise, lua executes the string itself.
+
+
+
+When called with option -E,
+besides ignoring LUA_INIT,
+Lua also ignores
+the values of LUA_PATH and LUA_CPATH,
+setting the values of
+package.path and package.cpath
+with the default paths defined in luaconf.h.
+
+
+
+All options are handled in order, except -i and -E.
+For instance, an invocation like
+
+
+ $ lua -e'a=1' -e 'print(a)' script.lua
+
+will first set a to 1, then print the value of a,
+and finally run the file script.lua with no arguments.
+(Here $ is the shell prompt. Your prompt may be different.)
+
+
+
+Before running any code,
+lua collects all command-line arguments
+in a global table called arg.
+The script name goes to 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 its options)
+go to negative indices.
+For instance, in the call
+
+
+If there is no script in the call,
+the interpreter name goes to index 0,
+followed by the other arguments.
+For instance, the call
+
+
+ $ lua -e "print(arg[1])"
+
+will print "-e".
+If there is a script,
+the script is called with parameters
+arg[1], ···, arg[#arg].
+(Like all chunks in Lua,
+the script is compiled as a vararg function.)
+
+
+
+In interactive mode,
+Lua repeatedly prompts and waits for a line.
+After reading a line,
+Lua first try to interpret the line as an expression.
+If it succeeds, it prints its value.
+Otherwise, it interprets the line as a statement.
+If you write an incomplete statement,
+the interpreter waits for its completion
+by issuing a different prompt.
+
+
+
+In case of unprotected errors in the script,
+the interpreter reports the error to the standard error stream.
+If the error object is not a string but
+has a metamethod __tostring,
+the interpreter calls this metamethod to produce the final message.
+Otherwise, the interpreter converts the error object to a string
+and adds a stack traceback to it.
+
+
+
+When finishing normally,
+the interpreter closes its main Lua state
+(see lua_close).
+The script can avoid this step by
+calling os.exit to terminate.
+
+
+
+To allow the use of Lua as a
+script interpreter in Unix systems,
+the standalone interpreter skips
+the first line of a chunk if it starts with #.
+Therefore, Lua scripts can be made into executable programs
+by using chmod +x and the #! form,
+as in
+
+
+ #!/usr/local/bin/lua
+
+(Of course,
+the location of the Lua interpreter may be different in your machine.
+If lua is in your PATH,
+then
+
+
+Here we list the incompatibilities that you may find when moving a program
+from Lua 5.2 to Lua 5.3.
+You can avoid some incompatibilities by compiling Lua with
+appropriate options (see file luaconf.h).
+However,
+all these compatibility options will be removed in the future.
+
+
+
+Lua versions can always change the C API in ways that
+do not imply source-code changes in a program,
+such as the numeric values for constants
+or the implementation of functions as macros.
+Therefore,
+you should not assume that binaries are compatible between
+different Lua versions.
+Always recompile clients of the Lua API when
+using a new version.
+
+
+
+Similarly, Lua versions can always change the internal representation
+of precompiled chunks;
+precompiled chunks are not compatible between different Lua versions.
+
+
+
+The standard paths in the official distribution may
+change between versions.
+
+
+
+
+The main difference between Lua 5.2 and Lua 5.3 is the
+introduction of an integer subtype for numbers.
+Although this change should not affect "normal" computations,
+some computations
+(mainly those that involve some kind of overflow)
+can give different results.
+
+
+
+You can fix these differences by forcing a number to be a float
+(in Lua 5.2 all numbers were float),
+in particular writing constants with an ending .0
+or using x = x + 0.0 to convert a variable.
+(This recommendation is only for a quick fix
+for an occasional incompatibility;
+it is not a general guideline for good programming.
+For good programming,
+use floats where you need floats
+and integers where you need integers.)
+
+
+
+The conversion of a float to a string now adds a .0 suffix
+to the result if it looks like an integer.
+(For instance, the float 2.0 will be printed as 2.0,
+not as 2.)
+You should always use an explicit format
+when you need a specific format for numbers.
+
+
+
+(Formally this is not an incompatibility,
+because Lua does not specify how numbers are formatted as strings,
+but some programs assumed a specific format.)
+
+
+
+The generational mode for the garbage collector was removed.
+(It was an experimental feature in Lua 5.2.)
+
+The bit32 library has been deprecated.
+It is easy to require a compatible external library or,
+better yet, to replace its functions with appropriate bitwise operations.
+(Keep in mind that bit32 operates on 32-bit integers,
+while the bitwise operators in standard Lua operate on 64-bit integers.)
+
+
+
+The Table library now respects metamethods
+for setting and getting elements.
+
+
+
+The ipairs iterator now respects metamethods and
+its __ipairs metamethod has been deprecated.
+
+
+
+Option names in io.read do not have a starting '*' anymore.
+For compatibility, Lua will continue to ignore this character.
+
+
+
+The following functions were deprecated in the mathematical library:
+atan2, cosh, sinh, tanh, pow,
+frexp, and ldexp.
+You can replace math.pow(x,y) with x^y;
+you can replace math.atan2 with math.atan,
+which now accepts one or two parameters;
+you can replace math.ldexp(x,exp) with x * 2.0^exp.
+For the other operations,
+you can either use an external library or
+implement them in Lua.
+
+
+
+The searcher for C loaders used by require
+changed the way it handles versioned names.
+Now, the version should come after the module name
+(as is usual in most other tools).
+For compatibility, that searcher still tries the old format
+if it cannot find an open function according to the new style.
+(Lua 5.2 already worked that way,
+but it did not document the change.)
+
+Continuation functions now receive as parameters what they needed
+to get through lua_getctx,
+so lua_getctx has been removed.
+Adapt your code accordingly.
+
+
+
+Function lua_dump has an extra parameter, strip.
+Use 0 as the value of this parameter to get the old behavior.
+
+
+
+Functions to inject/project unsigned integers
+(lua_pushunsigned, lua_tounsigned, lua_tounsignedx,
+luaL_checkunsigned, luaL_optunsigned)
+were deprecated.
+Use their signed equivalents with a type cast.
+
+
+
+Macros to project non-default integer types
+(luaL_checkint, luaL_optint, luaL_checklong, luaL_optlong)
+were deprecated.
+Use their equivalent over lua_Integer with a type cast
+(or, when possible, use lua_Integer in your code).
+
+Here is the complete syntax of Lua in extended BNF.
+As usual in extended BNF,
+{A} means 0 or more As,
+and [A] means an optional A.
+(For operator precedences, see §3.4.8;
+for a description of the terminals
+Name, Numeral,
+and LiteralString, see §3.1.)
+
+
+
+
+
+
+ chunk ::= block
+
+ block ::= {stat} [retstat]
+
+ stat ::= ‘;’ |
+ varlist ‘=’ explist |
+ functioncall |
+ label |
+ break |
+ goto Name |
+ do block end |
+ while exp do block end |
+ repeat block until exp |
+ if exp then block {elseif exp then block} [else block] end |
+ for Name ‘=’ exp ‘,’ exp [‘,’ exp] do block end |
+ for namelist in explist do block end |
+ function funcname funcbody |
+ localfunction Name funcbody |
+ local namelist [‘=’ explist]
+
+ retstat ::= return [explist] [‘;’]
+
+ label ::= ‘::’ Name ‘::’
+
+ funcname ::= Name {‘.’ Name} [‘:’ Name]
+
+ varlist ::= var {‘,’ var}
+
+ var ::= Name | prefixexp ‘[’ exp ‘]’ | prefixexp ‘.’ Name
+
+ namelist ::= Name {‘,’ Name}
+
+ explist ::= exp {‘,’ exp}
+
+ exp ::= nil | false | true | Numeral | LiteralString | ‘...’ | functiondef |
+ prefixexp | tableconstructor | exp binop exp | unop exp
+
+ prefixexp ::= var | functioncall | ‘(’ exp ‘)’
+
+ functioncall ::= prefixexp args | prefixexp ‘:’ Name args
+
+ args ::= ‘(’ [explist] ‘)’ | tableconstructor | LiteralString
+
+ functiondef ::= function funcbody
+
+ funcbody ::= ‘(’ [parlist] ‘)’ block end
+
+ parlist ::= namelist [‘,’ ‘...’] | ‘...’
+
+ tableconstructor ::= ‘{’ [fieldlist] ‘}’
+
+ fieldlist ::= field {fieldsep field} [fieldsep]
+
+ field ::= ‘[’ exp ‘]’ ‘=’ exp | Name ‘=’ exp | exp
+
+ fieldsep ::= ‘,’ | ‘;’
+
+ binop ::= ‘+’ | ‘-’ | ‘*’ | ‘/’ | ‘//’ | ‘^’ | ‘%’ |
+ ‘&’ | ‘~’ | ‘|’ | ‘>>’ | ‘<<’ | ‘..’ |
+ ‘<’ | ‘<=’ | ‘>’ | ‘>=’ | ‘==’ | ‘~=’ |
+ and | or
+
+ unop ::= ‘-’ | not | ‘#’ | ‘~’
+
+
+Lua is a powerful, fast, lightweight, embeddable scripting language
+developed by a
+team
+at
+PUC-Rio,
+the Pontifical Catholic University of Rio de Janeiro in Brazil.
+Lua is
+free software
+used in many products and projects around the world.
+
+
+Lua is distributed in
+source
+form.
+You need to build it before using it.
+Building Lua should be straightforward
+because
+Lua is implemented in pure ANSI C and compiles unmodified in all known
+platforms that have an ANSI C compiler.
+Lua also compiles unmodified as C++.
+The instructions given below for building Lua are for Unix-like platforms.
+See also
+instructions for other systems
+and
+customization options.
+
+
+If you don't have the time or the inclination to compile Lua yourself,
+get a binary from
+LuaBinaries.
+Try also
+LuaDist,
+a multi-platform distribution of Lua that includes batteries.
+
+
Building Lua
+
+
+In most Unix-like platforms, simply do "make" with a suitable target.
+Here are the details.
+
+
+
+Open a terminal window and move to
+the top-level directory, which is named lua-5.3.0.
+The Makefile there controls both the build process and the installation process.
+
+
+ Do "make" and see if your platform is listed.
+ The platforms currently supported are:
+
+
+ aix bsd c89 freebsd generic linux macosx mingw posix solaris
+
+
+ If your platform is listed, just do "make xxx", where xxx
+ is your platform name.
+
+ If your platform is not listed, try the closest one or posix, generic,
+ c89, in this order.
+
+
+The compilation takes only a few moments
+and produces three files in the src directory:
+lua (the interpreter),
+luac (the compiler),
+and liblua.a (the library).
+
+
+ To check that Lua has been built correctly, do "make test"
+ after building Lua. This will run the interpreter and print its version.
+
+
+If you're running Linux and get compilation errors,
+make sure you have installed the readline development package.
+If you get link errors after that,
+then try "make linux MYLIBS=-ltermcap".
+
+
Installing Lua
+
+ Once you have built Lua, you may want to install it in an official
+ place in your system. In this case, do "make install". The official
+ place and the way to install files are defined in the Makefile. You'll
+ probably need the right permissions to install files.
+
+
+ To build and install Lua in one step, do "make xxx install",
+ where xxx is your platform name.
+
+
+ To install Lua locally, do "make local".
+ This will create a directory install with subdirectories
+ bin, include, lib, man, share,
+ and install Lua as listed below.
+
+ To install Lua locally, but in some other directory, do
+ "make install INSTALL_TOP=xxx", where xxx is your chosen directory.
+ The installation starts in the src and doc directories,
+ so take care if INSTALL_TOP is not an absolute path.
+
+
+
+ bin:
+
+ lua luac
+
+ include:
+
+ lauxlib.h lua.h lua.hpp luaconf.h lualib.h
+
+ lib:
+
+ liblua.a
+
+ man/man1:
+
+ lua.1 luac.1
+
+
+
+ These are the only directories you need for development.
+ If you only want to run Lua programs,
+ you only need the files in bin and man.
+ The files in include and lib are needed for
+ embedding Lua in C or C++ programs.
+
+
+ Three kinds of things can be customized by editing a file:
+
+
Where and how to install Lua — edit Makefile.
+
How to build Lua — edit src/Makefile.
+
Lua features — edit src/luaconf.h.
+
+
+
+ You don't actually need to edit the Makefiles because you may set the
+ relevant variables in the command line when invoking make.
+ Nevertheless, it's probably best to edit and save the Makefiles to
+ record the changes you've made.
+
+
+ On the other hand, if you need to customize some Lua features, you'll need
+ to edit src/luaconf.h before building and installing Lua.
+ The edited file will be the one installed, and
+ it will be used by any Lua clients that you build, to ensure consistency.
+ Further customization is available to experts by editing the Lua sources.
+
+
+ If you're not using the usual Unix tools, then the instructions for
+ building Lua depend on the compiler you use. You'll need to create
+ projects (or whatever your compiler uses) for building the library,
+ the interpreter, and the compiler, as follows:
+
+
+ To use Lua as a library in your own programs you'll need to know how to
+ create and use libraries with your compiler. Moreover, to dynamically load
+ C libraries for Lua you'll need to know how to create dynamic libraries
+ and you'll need to make sure that the Lua API functions are accessible to
+ those dynamic libraries — but don't link the Lua library
+ into each dynamic library. For Unix, we recommend that the Lua library
+ be linked statically into the host program and its symbols exported for
+ dynamic linking; src/Makefile does this for the Lua interpreter.
+ For Windows, we recommend that the Lua library be a DLL.
+ In all cases, the compiler luac should be linked statically.
+
+
+ As mentioned above, you may edit src/luaconf.h to customize
+ some features before building Lua.
+
+
+Lua is free software distributed under the terms of the
+MIT license
+reproduced below;
+it may be used for any purpose, including commercial purposes,
+at absolutely no cost without having to ask us.
+
+The only requirement is that if you do use Lua,
+then you should give us credit by including the appropriate copyright notice somewhere in your product or its documentation.
+
+For details, see
+this.
+
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+
+
+
+
+Last update:
+Fri Dec 12 09:58:42 BRST 2014
+
+
+
+
+
diff --git a/lapi.c b/lapi.c
deleted file mode 100644
index 9b6ca1ecfb..0000000000
--- a/lapi.c
+++ /dev/null
@@ -1,1478 +0,0 @@
-/*
-** $Id: lapi.c $
-** Lua API
-** See Copyright Notice in lua.h
-*/
-
-#define lapi_c
-#define LUA_CORE
-
-#include "lprefix.h"
-
-
-#include
-#include
-#include
-
-#include "lua.h"
-
-#include "lapi.h"
-#include "ldebug.h"
-#include "ldo.h"
-#include "lfunc.h"
-#include "lgc.h"
-#include "lmem.h"
-#include "lobject.h"
-#include "lstate.h"
-#include "lstring.h"
-#include "ltable.h"
-#include "ltm.h"
-#include "lundump.h"
-#include "lvm.h"
-
-
-
-const char lua_ident[] =
- "$LuaVersion: " LUA_COPYRIGHT " $"
- "$LuaAuthors: " LUA_AUTHORS " $";
-
-
-
-/*
-** Test for a valid index (one that is not the 'nilvalue').
-*/
-#define isvalid(L, o) ((o) != &G(L)->nilvalue)
-
-
-/* test for pseudo index */
-#define ispseudo(i) ((i) <= LUA_REGISTRYINDEX)
-
-/* test for upvalue */
-#define isupvalue(i) ((i) < LUA_REGISTRYINDEX)
-
-
-/*
-** Convert an acceptable index to a pointer to its respective value.
-** Non-valid indices return the special nil value 'G(L)->nilvalue'.
-*/
-static TValue *index2value (lua_State *L, int idx) {
- CallInfo *ci = L->ci;
- if (idx > 0) {
- StkId o = ci->func.p + idx;
- api_check(L, idx <= ci->top.p - (ci->func.p + 1), "unacceptable index");
- if (o >= L->top.p) return &G(L)->nilvalue;
- else return s2v(o);
- }
- else if (!ispseudo(idx)) { /* negative index */
- api_check(L, idx != 0 && -idx <= L->top.p - (ci->func.p + 1),
- "invalid index");
- return s2v(L->top.p + idx);
- }
- else if (idx == LUA_REGISTRYINDEX)
- return &G(L)->l_registry;
- else { /* upvalues */
- idx = LUA_REGISTRYINDEX - idx;
- api_check(L, idx <= MAXUPVAL + 1, "upvalue index too large");
- if (ttisCclosure(s2v(ci->func.p))) { /* C closure? */
- CClosure *func = clCvalue(s2v(ci->func.p));
- return (idx <= func->nupvalues) ? &func->upvalue[idx-1]
- : &G(L)->nilvalue;
- }
- else { /* light C function or Lua function (through a hook)?) */
- api_check(L, ttislcf(s2v(ci->func.p)), "caller not a C function");
- return &G(L)->nilvalue; /* no upvalues */
- }
- }
-}
-
-
-
-/*
-** Convert a valid actual index (not a pseudo-index) to its address.
-*/
-static StkId index2stack (lua_State *L, int idx) {
- CallInfo *ci = L->ci;
- if (idx > 0) {
- StkId o = ci->func.p + idx;
- api_check(L, o < L->top.p, "invalid index");
- return o;
- }
- else { /* non-positive index */
- api_check(L, idx != 0 && -idx <= L->top.p - (ci->func.p + 1),
- "invalid index");
- api_check(L, !ispseudo(idx), "invalid index");
- return L->top.p + idx;
- }
-}
-
-
-LUA_API int lua_checkstack (lua_State *L, int n) {
- int res;
- CallInfo *ci;
- lua_lock(L);
- ci = L->ci;
- api_check(L, n >= 0, "negative 'n'");
- if (L->stack_last.p - L->top.p > n) /* stack large enough? */
- res = 1; /* yes; check is OK */
- else /* need to grow stack */
- res = luaD_growstack(L, n, 0);
- if (res && ci->top.p < L->top.p + n)
- ci->top.p = L->top.p + n; /* adjust frame top */
- lua_unlock(L);
- return res;
-}
-
-
-LUA_API void lua_xmove (lua_State *from, lua_State *to, int n) {
- int i;
- if (from == to) return;
- lua_lock(to);
- api_checkpop(from, n);
- api_check(from, G(from) == G(to), "moving among independent states");
- api_check(from, to->ci->top.p - to->top.p >= n, "stack overflow");
- from->top.p -= n;
- for (i = 0; i < n; i++) {
- setobjs2s(to, to->top.p, from->top.p + i);
- to->top.p++; /* stack already checked by previous 'api_check' */
- }
- lua_unlock(to);
-}
-
-
-LUA_API lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf) {
- lua_CFunction old;
- lua_lock(L);
- old = G(L)->panic;
- G(L)->panic = panicf;
- lua_unlock(L);
- return old;
-}
-
-
-LUA_API lua_Number lua_version (lua_State *L) {
- UNUSED(L);
- return LUA_VERSION_NUM;
-}
-
-
-
-/*
-** basic stack manipulation
-*/
-
-
-/*
-** convert an acceptable stack index into an absolute index
-*/
-LUA_API int lua_absindex (lua_State *L, int idx) {
- return (idx > 0 || ispseudo(idx))
- ? idx
- : cast_int(L->top.p - L->ci->func.p) + idx;
-}
-
-
-LUA_API int lua_gettop (lua_State *L) {
- return cast_int(L->top.p - (L->ci->func.p + 1));
-}
-
-
-LUA_API void lua_settop (lua_State *L, int idx) {
- CallInfo *ci;
- StkId func, newtop;
- ptrdiff_t diff; /* difference for new top */
- lua_lock(L);
- ci = L->ci;
- func = ci->func.p;
- if (idx >= 0) {
- api_check(L, idx <= ci->top.p - (func + 1), "new top too large");
- diff = ((func + 1) + idx) - L->top.p;
- for (; diff > 0; diff--)
- setnilvalue(s2v(L->top.p++)); /* clear new slots */
- }
- else {
- api_check(L, -(idx+1) <= (L->top.p - (func + 1)), "invalid new top");
- diff = idx + 1; /* will "subtract" index (as it is negative) */
- }
- newtop = L->top.p + diff;
- if (diff < 0 && L->tbclist.p >= newtop) {
- lua_assert(ci->callstatus & CIST_TBC);
- newtop = luaF_close(L, newtop, CLOSEKTOP, 0);
- }
- L->top.p = newtop; /* correct top only after closing any upvalue */
- lua_unlock(L);
-}
-
-
-LUA_API void lua_closeslot (lua_State *L, int idx) {
- StkId level;
- lua_lock(L);
- level = index2stack(L, idx);
- api_check(L, (L->ci->callstatus & CIST_TBC) && (L->tbclist.p == level),
- "no variable to close at given level");
- level = luaF_close(L, level, CLOSEKTOP, 0);
- setnilvalue(s2v(level));
- lua_unlock(L);
-}
-
-
-/*
-** Reverse the stack segment from 'from' to 'to'
-** (auxiliary to 'lua_rotate')
-** Note that we move(copy) only the value inside the stack.
-** (We do not move additional fields that may exist.)
-*/
-static void reverse (lua_State *L, StkId from, StkId to) {
- for (; from < to; from++, to--) {
- TValue temp;
- setobj(L, &temp, s2v(from));
- setobjs2s(L, from, to);
- setobj2s(L, to, &temp);
- }
-}
-
-
-/*
-** Let x = AB, where A is a prefix of length 'n'. Then,
-** rotate x n == BA. But BA == (A^r . B^r)^r.
-*/
-LUA_API void lua_rotate (lua_State *L, int idx, int n) {
- StkId p, t, m;
- lua_lock(L);
- t = L->top.p - 1; /* end of stack segment being rotated */
- p = index2stack(L, idx); /* start of segment */
- api_check(L, L->tbclist.p < p, "moving a to-be-closed slot");
- api_check(L, (n >= 0 ? n : -n) <= (t - p + 1), "invalid 'n'");
- m = (n >= 0 ? t - n : p - n - 1); /* end of prefix */
- reverse(L, p, m); /* reverse the prefix with length 'n' */
- reverse(L, m + 1, t); /* reverse the suffix */
- reverse(L, p, t); /* reverse the entire segment */
- lua_unlock(L);
-}
-
-
-LUA_API void lua_copy (lua_State *L, int fromidx, int toidx) {
- TValue *fr, *to;
- lua_lock(L);
- fr = index2value(L, fromidx);
- to = index2value(L, toidx);
- api_check(L, isvalid(L, to), "invalid index");
- setobj(L, to, fr);
- if (isupvalue(toidx)) /* function upvalue? */
- luaC_barrier(L, clCvalue(s2v(L->ci->func.p)), fr);
- /* LUA_REGISTRYINDEX does not need gc barrier
- (collector revisits it before finishing collection) */
- lua_unlock(L);
-}
-
-
-LUA_API void lua_pushvalue (lua_State *L, int idx) {
- lua_lock(L);
- setobj2s(L, L->top.p, index2value(L, idx));
- api_incr_top(L);
- lua_unlock(L);
-}
-
-
-
-/*
-** access functions (stack -> C)
-*/
-
-
-LUA_API int lua_type (lua_State *L, int idx) {
- const TValue *o = index2value(L, idx);
- return (isvalid(L, o) ? ttype(o) : LUA_TNONE);
-}
-
-
-LUA_API const char *lua_typename (lua_State *L, int t) {
- UNUSED(L);
- api_check(L, LUA_TNONE <= t && t < LUA_NUMTYPES, "invalid type");
- return ttypename(t);
-}
-
-
-LUA_API int lua_iscfunction (lua_State *L, int idx) {
- const TValue *o = index2value(L, idx);
- return (ttislcf(o) || (ttisCclosure(o)));
-}
-
-
-LUA_API int lua_isinteger (lua_State *L, int idx) {
- const TValue *o = index2value(L, idx);
- return ttisinteger(o);
-}
-
-
-LUA_API int lua_isnumber (lua_State *L, int idx) {
- lua_Number n;
- const TValue *o = index2value(L, idx);
- return tonumber(o, &n);
-}
-
-
-LUA_API int lua_isstring (lua_State *L, int idx) {
- const TValue *o = index2value(L, idx);
- return (ttisstring(o) || cvt2str(o));
-}
-
-
-LUA_API int lua_isuserdata (lua_State *L, int idx) {
- const TValue *o = index2value(L, idx);
- return (ttisfulluserdata(o) || ttislightuserdata(o));
-}
-
-
-LUA_API int lua_rawequal (lua_State *L, int index1, int index2) {
- const TValue *o1 = index2value(L, index1);
- const TValue *o2 = index2value(L, index2);
- return (isvalid(L, o1) && isvalid(L, o2)) ? luaV_rawequalobj(o1, o2) : 0;
-}
-
-
-LUA_API void lua_arith (lua_State *L, int op) {
- lua_lock(L);
- if (op != LUA_OPUNM && op != LUA_OPBNOT)
- api_checkpop(L, 2); /* all other operations expect two operands */
- else { /* for unary operations, add fake 2nd operand */
- api_checkpop(L, 1);
- setobjs2s(L, L->top.p, L->top.p - 1);
- api_incr_top(L);
- }
- /* first operand at top - 2, second at top - 1; result go to top - 2 */
- luaO_arith(L, op, s2v(L->top.p - 2), s2v(L->top.p - 1), L->top.p - 2);
- L->top.p--; /* pop second operand */
- lua_unlock(L);
-}
-
-
-LUA_API int lua_compare (lua_State *L, int index1, int index2, int op) {
- const TValue *o1;
- const TValue *o2;
- int i = 0;
- lua_lock(L); /* may call tag method */
- o1 = index2value(L, index1);
- o2 = index2value(L, index2);
- if (isvalid(L, o1) && isvalid(L, o2)) {
- switch (op) {
- case LUA_OPEQ: i = luaV_equalobj(L, o1, o2); break;
- case LUA_OPLT: i = luaV_lessthan(L, o1, o2); break;
- case LUA_OPLE: i = luaV_lessequal(L, o1, o2); break;
- default: api_check(L, 0, "invalid option");
- }
- }
- lua_unlock(L);
- return i;
-}
-
-
-LUA_API unsigned lua_numbertocstring (lua_State *L, int idx, char *buff) {
- const TValue *o = index2value(L, idx);
- if (ttisnumber(o)) {
- unsigned len = luaO_tostringbuff(o, buff);
- buff[len++] = '\0'; /* add final zero */
- return len;
- }
- else
- return 0;
-}
-
-
-LUA_API size_t lua_stringtonumber (lua_State *L, const char *s) {
- size_t sz = luaO_str2num(s, s2v(L->top.p));
- if (sz != 0)
- api_incr_top(L);
- return sz;
-}
-
-
-LUA_API lua_Number lua_tonumberx (lua_State *L, int idx, int *pisnum) {
- lua_Number n = 0;
- const TValue *o = index2value(L, idx);
- int isnum = tonumber(o, &n);
- if (pisnum)
- *pisnum = isnum;
- return n;
-}
-
-
-LUA_API lua_Integer lua_tointegerx (lua_State *L, int idx, int *pisnum) {
- lua_Integer res = 0;
- const TValue *o = index2value(L, idx);
- int isnum = tointeger(o, &res);
- if (pisnum)
- *pisnum = isnum;
- return res;
-}
-
-
-LUA_API int lua_toboolean (lua_State *L, int idx) {
- const TValue *o = index2value(L, idx);
- return !l_isfalse(o);
-}
-
-
-LUA_API const char *lua_tolstring (lua_State *L, int idx, size_t *len) {
- TValue *o;
- lua_lock(L);
- o = index2value(L, idx);
- if (!ttisstring(o)) {
- if (!cvt2str(o)) { /* not convertible? */
- if (len != NULL) *len = 0;
- lua_unlock(L);
- return NULL;
- }
- luaO_tostring(L, o);
- luaC_checkGC(L);
- o = index2value(L, idx); /* previous call may reallocate the stack */
- }
- lua_unlock(L);
- if (len != NULL)
- return getlstr(tsvalue(o), *len);
- else
- return getstr(tsvalue(o));
-}
-
-
-LUA_API lua_Unsigned lua_rawlen (lua_State *L, int idx) {
- const TValue *o = index2value(L, idx);
- switch (ttypetag(o)) {
- case LUA_VSHRSTR: return cast(lua_Unsigned, tsvalue(o)->shrlen);
- case LUA_VLNGSTR: return cast(lua_Unsigned, tsvalue(o)->u.lnglen);
- case LUA_VUSERDATA: return cast(lua_Unsigned, uvalue(o)->len);
- case LUA_VTABLE: {
- lua_Unsigned res;
- lua_lock(L);
- res = luaH_getn(L, hvalue(o));
- lua_unlock(L);
- return res;
- }
- default: return 0;
- }
-}
-
-
-LUA_API lua_CFunction lua_tocfunction (lua_State *L, int idx) {
- const TValue *o = index2value(L, idx);
- if (ttislcf(o)) return fvalue(o);
- else if (ttisCclosure(o))
- return clCvalue(o)->f;
- else return NULL; /* not a C function */
-}
-
-
-l_sinline void *touserdata (const TValue *o) {
- switch (ttype(o)) {
- case LUA_TUSERDATA: return getudatamem(uvalue(o));
- case LUA_TLIGHTUSERDATA: return pvalue(o);
- default: return NULL;
- }
-}
-
-
-LUA_API void *lua_touserdata (lua_State *L, int idx) {
- const TValue *o = index2value(L, idx);
- return touserdata(o);
-}
-
-
-LUA_API lua_State *lua_tothread (lua_State *L, int idx) {
- const TValue *o = index2value(L, idx);
- return (!ttisthread(o)) ? NULL : thvalue(o);
-}
-
-
-/*
-** Returns a pointer to the internal representation of an object.
-** Note that ISO C does not allow the conversion of a pointer to
-** function to a 'void*', so the conversion here goes through
-** a 'size_t'. (As the returned pointer is only informative, this
-** conversion should not be a problem.)
-*/
-LUA_API const void *lua_topointer (lua_State *L, int idx) {
- const TValue *o = index2value(L, idx);
- switch (ttypetag(o)) {
- case LUA_VLCF: return cast_voidp(cast_sizet(fvalue(o)));
- case LUA_VUSERDATA: case LUA_VLIGHTUSERDATA:
- return touserdata(o);
- default: {
- if (iscollectable(o))
- return gcvalue(o);
- else
- return NULL;
- }
- }
-}
-
-
-
-/*
-** push functions (C -> stack)
-*/
-
-
-LUA_API void lua_pushnil (lua_State *L) {
- lua_lock(L);
- setnilvalue(s2v(L->top.p));
- api_incr_top(L);
- lua_unlock(L);
-}
-
-
-LUA_API void lua_pushnumber (lua_State *L, lua_Number n) {
- lua_lock(L);
- setfltvalue(s2v(L->top.p), n);
- api_incr_top(L);
- lua_unlock(L);
-}
-
-
-LUA_API void lua_pushinteger (lua_State *L, lua_Integer n) {
- lua_lock(L);
- setivalue(s2v(L->top.p), n);
- api_incr_top(L);
- lua_unlock(L);
-}
-
-
-/*
-** Pushes on the stack a string with given length. Avoid using 's' when
-** 'len' == 0 (as 's' can be NULL in that case), due to later use of
-** 'memcmp' and 'memcpy'.
-*/
-LUA_API const char *lua_pushlstring (lua_State *L, const char *s, size_t len) {
- TString *ts;
- lua_lock(L);
- ts = (len == 0) ? luaS_new(L, "") : luaS_newlstr(L, s, len);
- setsvalue2s(L, L->top.p, ts);
- api_incr_top(L);
- luaC_checkGC(L);
- lua_unlock(L);
- return getstr(ts);
-}
-
-
-LUA_API const char *lua_pushexternalstring (lua_State *L,
- const char *s, size_t len, lua_Alloc falloc, void *ud) {
- TString *ts;
- lua_lock(L);
- api_check(L, len <= MAX_SIZE, "string too large");
- api_check(L, s[len] == '\0', "string not ending with zero");
- ts = luaS_newextlstr (L, s, len, falloc, ud);
- setsvalue2s(L, L->top.p, ts);
- api_incr_top(L);
- luaC_checkGC(L);
- lua_unlock(L);
- return getstr(ts);
-}
-
-
-LUA_API const char *lua_pushstring (lua_State *L, const char *s) {
- lua_lock(L);
- if (s == NULL)
- setnilvalue(s2v(L->top.p));
- else {
- TString *ts;
- ts = luaS_new(L, s);
- setsvalue2s(L, L->top.p, ts);
- s = getstr(ts); /* internal copy's address */
- }
- api_incr_top(L);
- luaC_checkGC(L);
- lua_unlock(L);
- return s;
-}
-
-
-LUA_API const char *lua_pushvfstring (lua_State *L, const char *fmt,
- va_list argp) {
- const char *ret;
- lua_lock(L);
- ret = luaO_pushvfstring(L, fmt, argp);
- luaC_checkGC(L);
- lua_unlock(L);
- return ret;
-}
-
-
-LUA_API const char *lua_pushfstring (lua_State *L, const char *fmt, ...) {
- const char *ret;
- va_list argp;
- lua_lock(L);
- pushvfstring(L, argp, fmt, ret);
- luaC_checkGC(L);
- lua_unlock(L);
- return ret;
-}
-
-
-LUA_API void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n) {
- lua_lock(L);
- if (n == 0) {
- setfvalue(s2v(L->top.p), fn);
- api_incr_top(L);
- }
- else {
- int i;
- CClosure *cl;
- api_checkpop(L, n);
- api_check(L, n <= MAXUPVAL, "upvalue index too large");
- cl = luaF_newCclosure(L, n);
- cl->f = fn;
- for (i = 0; i < n; i++) {
- setobj2n(L, &cl->upvalue[i], s2v(L->top.p - n + i));
- /* does not need barrier because closure is white */
- lua_assert(iswhite(cl));
- }
- L->top.p -= n;
- setclCvalue(L, s2v(L->top.p), cl);
- api_incr_top(L);
- luaC_checkGC(L);
- }
- lua_unlock(L);
-}
-
-
-LUA_API void lua_pushboolean (lua_State *L, int b) {
- lua_lock(L);
- if (b)
- setbtvalue(s2v(L->top.p));
- else
- setbfvalue(s2v(L->top.p));
- api_incr_top(L);
- lua_unlock(L);
-}
-
-
-LUA_API void lua_pushlightuserdata (lua_State *L, void *p) {
- lua_lock(L);
- setpvalue(s2v(L->top.p), p);
- api_incr_top(L);
- lua_unlock(L);
-}
-
-
-LUA_API int lua_pushthread (lua_State *L) {
- lua_lock(L);
- setthvalue(L, s2v(L->top.p), L);
- api_incr_top(L);
- lua_unlock(L);
- return (mainthread(G(L)) == L);
-}
-
-
-
-/*
-** get functions (Lua -> stack)
-*/
-
-
-static int auxgetstr (lua_State *L, const TValue *t, const char *k) {
- lu_byte tag;
- TString *str = luaS_new(L, k);
- luaV_fastget(t, str, s2v(L->top.p), luaH_getstr, tag);
- if (!tagisempty(tag))
- api_incr_top(L);
- else {
- setsvalue2s(L, L->top.p, str);
- api_incr_top(L);
- tag = luaV_finishget(L, t, s2v(L->top.p - 1), L->top.p - 1, tag);
- }
- lua_unlock(L);
- return novariant(tag);
-}
-
-
-/*
-** The following function assumes that the registry cannot be a weak
-** table; so, an emergency collection while using the global table
-** cannot collect it.
-*/
-static void getGlobalTable (lua_State *L, TValue *gt) {
- Table *registry = hvalue(&G(L)->l_registry);
- lu_byte tag = luaH_getint(registry, LUA_RIDX_GLOBALS, gt);
- (void)tag; /* avoid not-used warnings when checks are off */
- api_check(L, novariant(tag) == LUA_TTABLE, "global table must exist");
-}
-
-
-LUA_API int lua_getglobal (lua_State *L, const char *name) {
- TValue gt;
- lua_lock(L);
- getGlobalTable(L, >);
- return auxgetstr(L, >, name);
-}
-
-
-LUA_API int lua_gettable (lua_State *L, int idx) {
- lu_byte tag;
- TValue *t;
- lua_lock(L);
- api_checkpop(L, 1);
- t = index2value(L, idx);
- luaV_fastget(t, s2v(L->top.p - 1), s2v(L->top.p - 1), luaH_get, tag);
- if (tagisempty(tag))
- tag = luaV_finishget(L, t, s2v(L->top.p - 1), L->top.p - 1, tag);
- lua_unlock(L);
- return novariant(tag);
-}
-
-
-LUA_API int lua_getfield (lua_State *L, int idx, const char *k) {
- lua_lock(L);
- return auxgetstr(L, index2value(L, idx), k);
-}
-
-
-LUA_API int lua_geti (lua_State *L, int idx, lua_Integer n) {
- TValue *t;
- lu_byte tag;
- lua_lock(L);
- t = index2value(L, idx);
- luaV_fastgeti(t, n, s2v(L->top.p), tag);
- if (tagisempty(tag)) {
- TValue key;
- setivalue(&key, n);
- tag = luaV_finishget(L, t, &key, L->top.p, tag);
- }
- api_incr_top(L);
- lua_unlock(L);
- return novariant(tag);
-}
-
-
-static int finishrawget (lua_State *L, lu_byte tag) {
- if (tagisempty(tag)) /* avoid copying empty items to the stack */
- setnilvalue(s2v(L->top.p));
- api_incr_top(L);
- lua_unlock(L);
- return novariant(tag);
-}
-
-
-l_sinline Table *gettable (lua_State *L, int idx) {
- TValue *t = index2value(L, idx);
- api_check(L, ttistable(t), "table expected");
- return hvalue(t);
-}
-
-
-LUA_API int lua_rawget (lua_State *L, int idx) {
- Table *t;
- lu_byte tag;
- lua_lock(L);
- api_checkpop(L, 1);
- t = gettable(L, idx);
- tag = luaH_get(t, s2v(L->top.p - 1), s2v(L->top.p - 1));
- L->top.p--; /* pop key */
- return finishrawget(L, tag);
-}
-
-
-LUA_API int lua_rawgeti (lua_State *L, int idx, lua_Integer n) {
- Table *t;
- lu_byte tag;
- lua_lock(L);
- t = gettable(L, idx);
- luaH_fastgeti(t, n, s2v(L->top.p), tag);
- return finishrawget(L, tag);
-}
-
-
-LUA_API int lua_rawgetp (lua_State *L, int idx, const void *p) {
- Table *t;
- TValue k;
- lua_lock(L);
- t = gettable(L, idx);
- setpvalue(&k, cast_voidp(p));
- return finishrawget(L, luaH_get(t, &k, s2v(L->top.p)));
-}
-
-
-LUA_API void lua_createtable (lua_State *L, int narray, int nrec) {
- Table *t;
- lua_lock(L);
- t = luaH_new(L);
- sethvalue2s(L, L->top.p, t);
- api_incr_top(L);
- if (narray > 0 || nrec > 0)
- luaH_resize(L, t, cast_uint(narray), cast_uint(nrec));
- luaC_checkGC(L);
- lua_unlock(L);
-}
-
-
-LUA_API int lua_getmetatable (lua_State *L, int objindex) {
- const TValue *obj;
- Table *mt;
- int res = 0;
- lua_lock(L);
- obj = index2value(L, objindex);
- switch (ttype(obj)) {
- case LUA_TTABLE:
- mt = hvalue(obj)->metatable;
- break;
- case LUA_TUSERDATA:
- mt = uvalue(obj)->metatable;
- break;
- default:
- mt = G(L)->mt[ttype(obj)];
- break;
- }
- if (mt != NULL) {
- sethvalue2s(L, L->top.p, mt);
- api_incr_top(L);
- res = 1;
- }
- lua_unlock(L);
- return res;
-}
-
-
-LUA_API int lua_getiuservalue (lua_State *L, int idx, int n) {
- TValue *o;
- int t;
- lua_lock(L);
- o = index2value(L, idx);
- api_check(L, ttisfulluserdata(o), "full userdata expected");
- if (n <= 0 || n > uvalue(o)->nuvalue) {
- setnilvalue(s2v(L->top.p));
- t = LUA_TNONE;
- }
- else {
- setobj2s(L, L->top.p, &uvalue(o)->uv[n - 1].uv);
- t = ttype(s2v(L->top.p));
- }
- api_incr_top(L);
- lua_unlock(L);
- return t;
-}
-
-
-/*
-** set functions (stack -> Lua)
-*/
-
-/*
-** t[k] = value at the top of the stack (where 'k' is a string)
-*/
-static void auxsetstr (lua_State *L, const TValue *t, const char *k) {
- int hres;
- TString *str = luaS_new(L, k);
- api_checkpop(L, 1);
- luaV_fastset(t, str, s2v(L->top.p - 1), hres, luaH_psetstr);
- if (hres == HOK) {
- luaV_finishfastset(L, t, s2v(L->top.p - 1));
- L->top.p--; /* pop value */
- }
- else {
- setsvalue2s(L, L->top.p, str); /* push 'str' (to make it a TValue) */
- api_incr_top(L);
- luaV_finishset(L, t, s2v(L->top.p - 1), s2v(L->top.p - 2), hres);
- L->top.p -= 2; /* pop value and key */
- }
- lua_unlock(L); /* lock done by caller */
-}
-
-
-LUA_API void lua_setglobal (lua_State *L, const char *name) {
- TValue gt;
- lua_lock(L); /* unlock done in 'auxsetstr' */
- getGlobalTable(L, >);
- auxsetstr(L, >, name);
-}
-
-
-LUA_API void lua_settable (lua_State *L, int idx) {
- TValue *t;
- int hres;
- lua_lock(L);
- api_checkpop(L, 2);
- t = index2value(L, idx);
- luaV_fastset(t, s2v(L->top.p - 2), s2v(L->top.p - 1), hres, luaH_pset);
- if (hres == HOK)
- luaV_finishfastset(L, t, s2v(L->top.p - 1));
- else
- luaV_finishset(L, t, s2v(L->top.p - 2), s2v(L->top.p - 1), hres);
- L->top.p -= 2; /* pop index and value */
- lua_unlock(L);
-}
-
-
-LUA_API void lua_setfield (lua_State *L, int idx, const char *k) {
- lua_lock(L); /* unlock done in 'auxsetstr' */
- auxsetstr(L, index2value(L, idx), k);
-}
-
-
-LUA_API void lua_seti (lua_State *L, int idx, lua_Integer n) {
- TValue *t;
- int hres;
- lua_lock(L);
- api_checkpop(L, 1);
- t = index2value(L, idx);
- luaV_fastseti(t, n, s2v(L->top.p - 1), hres);
- if (hres == HOK)
- luaV_finishfastset(L, t, s2v(L->top.p - 1));
- else {
- TValue temp;
- setivalue(&temp, n);
- luaV_finishset(L, t, &temp, s2v(L->top.p - 1), hres);
- }
- L->top.p--; /* pop value */
- lua_unlock(L);
-}
-
-
-static void aux_rawset (lua_State *L, int idx, TValue *key, int n) {
- Table *t;
- lua_lock(L);
- api_checkpop(L, n);
- t = gettable(L, idx);
- luaH_set(L, t, key, s2v(L->top.p - 1));
- invalidateTMcache(t);
- luaC_barrierback(L, obj2gco(t), s2v(L->top.p - 1));
- L->top.p -= n;
- lua_unlock(L);
-}
-
-
-LUA_API void lua_rawset (lua_State *L, int idx) {
- aux_rawset(L, idx, s2v(L->top.p - 2), 2);
-}
-
-
-LUA_API void lua_rawsetp (lua_State *L, int idx, const void *p) {
- TValue k;
- setpvalue(&k, cast_voidp(p));
- aux_rawset(L, idx, &k, 1);
-}
-
-
-LUA_API void lua_rawseti (lua_State *L, int idx, lua_Integer n) {
- Table *t;
- lua_lock(L);
- api_checkpop(L, 1);
- t = gettable(L, idx);
- luaH_setint(L, t, n, s2v(L->top.p - 1));
- luaC_barrierback(L, obj2gco(t), s2v(L->top.p - 1));
- L->top.p--;
- lua_unlock(L);
-}
-
-
-LUA_API int lua_setmetatable (lua_State *L, int objindex) {
- TValue *obj;
- Table *mt;
- lua_lock(L);
- api_checkpop(L, 1);
- obj = index2value(L, objindex);
- if (ttisnil(s2v(L->top.p - 1)))
- mt = NULL;
- else {
- api_check(L, ttistable(s2v(L->top.p - 1)), "table expected");
- mt = hvalue(s2v(L->top.p - 1));
- }
- switch (ttype(obj)) {
- case LUA_TTABLE: {
- hvalue(obj)->metatable = mt;
- if (mt) {
- luaC_objbarrier(L, gcvalue(obj), mt);
- luaC_checkfinalizer(L, gcvalue(obj), mt);
- }
- break;
- }
- case LUA_TUSERDATA: {
- uvalue(obj)->metatable = mt;
- if (mt) {
- luaC_objbarrier(L, uvalue(obj), mt);
- luaC_checkfinalizer(L, gcvalue(obj), mt);
- }
- break;
- }
- default: {
- G(L)->mt[ttype(obj)] = mt;
- break;
- }
- }
- L->top.p--;
- lua_unlock(L);
- return 1;
-}
-
-
-LUA_API int lua_setiuservalue (lua_State *L, int idx, int n) {
- TValue *o;
- int res;
- lua_lock(L);
- api_checkpop(L, 1);
- o = index2value(L, idx);
- api_check(L, ttisfulluserdata(o), "full userdata expected");
- if (!(cast_uint(n) - 1u < cast_uint(uvalue(o)->nuvalue)))
- res = 0; /* 'n' not in [1, uvalue(o)->nuvalue] */
- else {
- setobj(L, &uvalue(o)->uv[n - 1].uv, s2v(L->top.p - 1));
- luaC_barrierback(L, gcvalue(o), s2v(L->top.p - 1));
- res = 1;
- }
- L->top.p--;
- lua_unlock(L);
- return res;
-}
-
-
-/*
-** 'load' and 'call' functions (run Lua code)
-*/
-
-
-#define checkresults(L,na,nr) \
- (api_check(L, (nr) == LUA_MULTRET \
- || (L->ci->top.p - L->top.p >= (nr) - (na)), \
- "results from function overflow current stack size"), \
- api_check(L, LUA_MULTRET <= (nr) && (nr) <= MAXRESULTS, \
- "invalid number of results"))
-
-
-LUA_API void lua_callk (lua_State *L, int nargs, int nresults,
- lua_KContext ctx, lua_KFunction k) {
- StkId func;
- lua_lock(L);
- api_check(L, k == NULL || !isLua(L->ci),
- "cannot use continuations inside hooks");
- api_checkpop(L, nargs + 1);
- api_check(L, L->status == LUA_OK, "cannot do calls on non-normal thread");
- checkresults(L, nargs, nresults);
- func = L->top.p - (nargs+1);
- if (k != NULL && yieldable(L)) { /* need to prepare continuation? */
- L->ci->u.c.k = k; /* save continuation */
- L->ci->u.c.ctx = ctx; /* save context */
- luaD_call(L, func, nresults); /* do the call */
- }
- else /* no continuation or no yieldable */
- luaD_callnoyield(L, func, nresults); /* just do the call */
- adjustresults(L, nresults);
- lua_unlock(L);
-}
-
-
-
-/*
-** Execute a protected call.
-*/
-struct CallS { /* data to 'f_call' */
- StkId func;
- int nresults;
-};
-
-
-static void f_call (lua_State *L, void *ud) {
- struct CallS *c = cast(struct CallS *, ud);
- luaD_callnoyield(L, c->func, c->nresults);
-}
-
-
-
-LUA_API int lua_pcallk (lua_State *L, int nargs, int nresults, int errfunc,
- lua_KContext ctx, lua_KFunction k) {
- struct CallS c;
- TStatus status;
- ptrdiff_t func;
- lua_lock(L);
- api_check(L, k == NULL || !isLua(L->ci),
- "cannot use continuations inside hooks");
- api_checkpop(L, nargs + 1);
- api_check(L, L->status == LUA_OK, "cannot do calls on non-normal thread");
- checkresults(L, nargs, nresults);
- if (errfunc == 0)
- func = 0;
- else {
- StkId o = index2stack(L, errfunc);
- api_check(L, ttisfunction(s2v(o)), "error handler must be a function");
- func = savestack(L, o);
- }
- c.func = L->top.p - (nargs+1); /* function to be called */
- if (k == NULL || !yieldable(L)) { /* no continuation or no yieldable? */
- c.nresults = nresults; /* do a 'conventional' protected call */
- status = luaD_pcall(L, f_call, &c, savestack(L, c.func), func);
- }
- else { /* prepare continuation (call is already protected by 'resume') */
- CallInfo *ci = L->ci;
- ci->u.c.k = k; /* save continuation */
- ci->u.c.ctx = ctx; /* save context */
- /* save information for error recovery */
- ci->u2.funcidx = cast_int(savestack(L, c.func));
- ci->u.c.old_errfunc = L->errfunc;
- L->errfunc = func;
- setoah(ci, L->allowhook); /* save value of 'allowhook' */
- ci->callstatus |= CIST_YPCALL; /* function can do error recovery */
- luaD_call(L, c.func, nresults); /* do the call */
- ci->callstatus &= ~CIST_YPCALL;
- L->errfunc = ci->u.c.old_errfunc;
- status = LUA_OK; /* if it is here, there were no errors */
- }
- adjustresults(L, nresults);
- lua_unlock(L);
- return APIstatus(status);
-}
-
-
-LUA_API int lua_load (lua_State *L, lua_Reader reader, void *data,
- const char *chunkname, const char *mode) {
- ZIO z;
- TStatus status;
- lua_lock(L);
- if (!chunkname) chunkname = "?";
- luaZ_init(L, &z, reader, data);
- status = luaD_protectedparser(L, &z, chunkname, mode);
- if (status == LUA_OK) { /* no errors? */
- LClosure *f = clLvalue(s2v(L->top.p - 1)); /* get new function */
- if (f->nupvalues >= 1) { /* does it have an upvalue? */
- /* get global table from registry */
- TValue gt;
- getGlobalTable(L, >);
- /* set global table as 1st upvalue of 'f' (may be LUA_ENV) */
- setobj(L, f->upvals[0]->v.p, >);
- luaC_barrier(L, f->upvals[0], >);
- }
- }
- lua_unlock(L);
- return APIstatus(status);
-}
-
-
-/*
-** Dump a Lua function, calling 'writer' to write its parts. Ensure
-** the stack returns with its original size.
-*/
-LUA_API int lua_dump (lua_State *L, lua_Writer writer, void *data, int strip) {
- int status;
- ptrdiff_t otop = savestack(L, L->top.p); /* original top */
- TValue *f = s2v(L->top.p - 1); /* function to be dumped */
- lua_lock(L);
- api_checkpop(L, 1);
- api_check(L, isLfunction(f), "Lua function expected");
- status = luaU_dump(L, clLvalue(f)->p, writer, data, strip);
- L->top.p = restorestack(L, otop); /* restore top */
- lua_unlock(L);
- return status;
-}
-
-
-LUA_API int lua_status (lua_State *L) {
- return APIstatus(L->status);
-}
-
-
-/*
-** Garbage-collection function
-*/
-LUA_API int lua_gc (lua_State *L, int what, ...) {
- va_list argp;
- int res = 0;
- global_State *g = G(L);
- if (g->gcstp & (GCSTPGC | GCSTPCLS)) /* internal stop? */
- return -1; /* all options are invalid when stopped */
- lua_lock(L);
- va_start(argp, what);
- switch (what) {
- case LUA_GCSTOP: {
- g->gcstp = GCSTPUSR; /* stopped by the user */
- break;
- }
- case LUA_GCRESTART: {
- luaE_setdebt(g, 0);
- g->gcstp = 0; /* (other bits must be zero here) */
- break;
- }
- case LUA_GCCOLLECT: {
- luaC_fullgc(L, 0);
- break;
- }
- case LUA_GCCOUNT: {
- /* GC values are expressed in Kbytes: #bytes/2^10 */
- res = cast_int(gettotalbytes(g) >> 10);
- break;
- }
- case LUA_GCCOUNTB: {
- res = cast_int(gettotalbytes(g) & 0x3ff);
- break;
- }
- case LUA_GCSTEP: {
- lu_byte oldstp = g->gcstp;
- l_mem n = cast(l_mem, va_arg(argp, size_t));
- l_mem newdebt;
- int work = 0; /* true if GC did some work */
- g->gcstp = 0; /* allow GC to run (other bits must be zero here) */
- if (n <= 0)
- newdebt = 0; /* force to run one basic step */
- else if (g->GCdebt >= n - MAX_LMEM) /* no overflow? */
- newdebt = g->GCdebt - n;
- else /* overflow */
- newdebt = -MAX_LMEM; /* set debt to miminum value */
- luaE_setdebt(g, newdebt);
- luaC_condGC(L, (void)0, work = 1);
- if (work && g->gcstate == GCSpause) /* end of cycle? */
- res = 1; /* signal it */
- g->gcstp = oldstp; /* restore previous state */
- break;
- }
- case LUA_GCISRUNNING: {
- res = gcrunning(g);
- break;
- }
- case LUA_GCGEN: {
- res = (g->gckind == KGC_INC) ? LUA_GCINC : LUA_GCGEN;
- luaC_changemode(L, KGC_GENMINOR);
- break;
- }
- case LUA_GCINC: {
- res = (g->gckind == KGC_INC) ? LUA_GCINC : LUA_GCGEN;
- luaC_changemode(L, KGC_INC);
- break;
- }
- case LUA_GCPARAM: {
- int param = va_arg(argp, int);
- int value = va_arg(argp, int);
- api_check(L, 0 <= param && param < LUA_GCPN, "invalid parameter");
- res = cast_int(luaO_applyparam(g->gcparams[param], 100));
- if (value >= 0)
- g->gcparams[param] = luaO_codeparam(cast_uint(value));
- break;
- }
- default: res = -1; /* invalid option */
- }
- va_end(argp);
- lua_unlock(L);
- return res;
-}
-
-
-
-/*
-** miscellaneous functions
-*/
-
-
-LUA_API int lua_error (lua_State *L) {
- TValue *errobj;
- lua_lock(L);
- errobj = s2v(L->top.p - 1);
- api_checkpop(L, 1);
- /* error object is the memory error message? */
- if (ttisshrstring(errobj) && eqshrstr(tsvalue(errobj), G(L)->memerrmsg))
- luaM_error(L); /* raise a memory error */
- else
- luaG_errormsg(L); /* raise a regular error */
- /* code unreachable; will unlock when control actually leaves the kernel */
- return 0; /* to avoid warnings */
-}
-
-
-LUA_API int lua_next (lua_State *L, int idx) {
- Table *t;
- int more;
- lua_lock(L);
- api_checkpop(L, 1);
- t = gettable(L, idx);
- more = luaH_next(L, t, L->top.p - 1);
- if (more)
- api_incr_top(L);
- else /* no more elements */
- L->top.p--; /* pop key */
- lua_unlock(L);
- return more;
-}
-
-
-LUA_API void lua_toclose (lua_State *L, int idx) {
- StkId o;
- lua_lock(L);
- o = index2stack(L, idx);
- api_check(L, L->tbclist.p < o, "given index below or equal a marked one");
- luaF_newtbcupval(L, o); /* create new to-be-closed upvalue */
- L->ci->callstatus |= CIST_TBC; /* mark that function has TBC slots */
- lua_unlock(L);
-}
-
-
-LUA_API void lua_concat (lua_State *L, int n) {
- lua_lock(L);
- api_checknelems(L, n);
- if (n > 0) {
- luaV_concat(L, n);
- luaC_checkGC(L);
- }
- else { /* nothing to concatenate */
- setsvalue2s(L, L->top.p, luaS_newlstr(L, "", 0)); /* push empty string */
- api_incr_top(L);
- }
- lua_unlock(L);
-}
-
-
-LUA_API void lua_len (lua_State *L, int idx) {
- TValue *t;
- lua_lock(L);
- t = index2value(L, idx);
- luaV_objlen(L, L->top.p, t);
- api_incr_top(L);
- lua_unlock(L);
-}
-
-
-LUA_API lua_Alloc lua_getallocf (lua_State *L, void **ud) {
- lua_Alloc f;
- lua_lock(L);
- if (ud) *ud = G(L)->ud;
- f = G(L)->frealloc;
- lua_unlock(L);
- return f;
-}
-
-
-LUA_API void lua_setallocf (lua_State *L, lua_Alloc f, void *ud) {
- lua_lock(L);
- G(L)->ud = ud;
- G(L)->frealloc = f;
- lua_unlock(L);
-}
-
-
-void lua_setwarnf (lua_State *L, lua_WarnFunction f, void *ud) {
- lua_lock(L);
- G(L)->ud_warn = ud;
- G(L)->warnf = f;
- lua_unlock(L);
-}
-
-
-void lua_warning (lua_State *L, const char *msg, int tocont) {
- lua_lock(L);
- luaE_warning(L, msg, tocont);
- lua_unlock(L);
-}
-
-
-
-LUA_API void *lua_newuserdatauv (lua_State *L, size_t size, int nuvalue) {
- Udata *u;
- lua_lock(L);
- api_check(L, 0 <= nuvalue && nuvalue < SHRT_MAX, "invalid value");
- u = luaS_newudata(L, size, cast(unsigned short, nuvalue));
- setuvalue(L, s2v(L->top.p), u);
- api_incr_top(L);
- luaC_checkGC(L);
- lua_unlock(L);
- return getudatamem(u);
-}
-
-
-
-static const char *aux_upvalue (TValue *fi, int n, TValue **val,
- GCObject **owner) {
- switch (ttypetag(fi)) {
- case LUA_VCCL: { /* C closure */
- CClosure *f = clCvalue(fi);
- if (!(cast_uint(n) - 1u < cast_uint(f->nupvalues)))
- return NULL; /* 'n' not in [1, f->nupvalues] */
- *val = &f->upvalue[n-1];
- if (owner) *owner = obj2gco(f);
- return "";
- }
- case LUA_VLCL: { /* Lua closure */
- LClosure *f = clLvalue(fi);
- TString *name;
- Proto *p = f->p;
- if (!(cast_uint(n) - 1u < cast_uint(p->sizeupvalues)))
- return NULL; /* 'n' not in [1, p->sizeupvalues] */
- *val = f->upvals[n-1]->v.p;
- if (owner) *owner = obj2gco(f->upvals[n - 1]);
- name = p->upvalues[n-1].name;
- return (name == NULL) ? "(no name)" : getstr(name);
- }
- default: return NULL; /* not a closure */
- }
-}
-
-
-LUA_API const char *lua_getupvalue (lua_State *L, int funcindex, int n) {
- const char *name;
- TValue *val = NULL; /* to avoid warnings */
- lua_lock(L);
- name = aux_upvalue(index2value(L, funcindex), n, &val, NULL);
- if (name) {
- setobj2s(L, L->top.p, val);
- api_incr_top(L);
- }
- lua_unlock(L);
- return name;
-}
-
-
-LUA_API const char *lua_setupvalue (lua_State *L, int funcindex, int n) {
- const char *name;
- TValue *val = NULL; /* to avoid warnings */
- GCObject *owner = NULL; /* to avoid warnings */
- TValue *fi;
- lua_lock(L);
- fi = index2value(L, funcindex);
- api_checknelems(L, 1);
- name = aux_upvalue(fi, n, &val, &owner);
- if (name) {
- L->top.p--;
- setobj(L, val, s2v(L->top.p));
- luaC_barrier(L, owner, val);
- }
- lua_unlock(L);
- return name;
-}
-
-
-static UpVal **getupvalref (lua_State *L, int fidx, int n, LClosure **pf) {
- static const UpVal *const nullup = NULL;
- LClosure *f;
- TValue *fi = index2value(L, fidx);
- api_check(L, ttisLclosure(fi), "Lua function expected");
- f = clLvalue(fi);
- if (pf) *pf = f;
- if (1 <= n && n <= f->p->sizeupvalues)
- return &f->upvals[n - 1]; /* get its upvalue pointer */
- else
- return (UpVal**)&nullup;
-}
-
-
-LUA_API void *lua_upvalueid (lua_State *L, int fidx, int n) {
- TValue *fi = index2value(L, fidx);
- switch (ttypetag(fi)) {
- case LUA_VLCL: { /* lua closure */
- return *getupvalref(L, fidx, n, NULL);
- }
- case LUA_VCCL: { /* C closure */
- CClosure *f = clCvalue(fi);
- if (1 <= n && n <= f->nupvalues)
- return &f->upvalue[n - 1];
- /* else */
- } /* FALLTHROUGH */
- case LUA_VLCF:
- return NULL; /* light C functions have no upvalues */
- default: {
- api_check(L, 0, "function expected");
- return NULL;
- }
- }
-}
-
-
-LUA_API void lua_upvaluejoin (lua_State *L, int fidx1, int n1,
- int fidx2, int n2) {
- LClosure *f1;
- UpVal **up1 = getupvalref(L, fidx1, n1, &f1);
- UpVal **up2 = getupvalref(L, fidx2, n2, NULL);
- api_check(L, *up1 != NULL && *up2 != NULL, "invalid upvalue index");
- *up1 = *up2;
- luaC_objbarrier(L, f1, *up1);
-}
-
-
diff --git a/lapi.h b/lapi.h
deleted file mode 100644
index 9b54534428..0000000000
--- a/lapi.h
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
-** $Id: lapi.h $
-** Auxiliary functions from Lua API
-** See Copyright Notice in lua.h
-*/
-
-#ifndef lapi_h
-#define lapi_h
-
-
-#include "llimits.h"
-#include "lstate.h"
-
-
-#if defined(LUA_USE_APICHECK)
-#include
-#define api_check(l,e,msg) assert(e)
-#else /* for testing */
-#define api_check(l,e,msg) ((void)(l), lua_assert((e) && msg))
-#endif
-
-
-
-/* Increments 'L->top.p', checking for stack overflows */
-#define api_incr_top(L) \
- (L->top.p++, api_check(L, L->top.p <= L->ci->top.p, "stack overflow"))
-
-
-/*
-** macros that are executed whenever program enters the Lua core
-** ('lua_lock') and leaves the core ('lua_unlock')
-*/
-#if !defined(lua_lock)
-#define lua_lock(L) ((void) 0)
-#define lua_unlock(L) ((void) 0)
-#endif
-
-
-
-/*
-** If a call returns too many multiple returns, the callee may not have
-** stack space to accommodate all results. In this case, this macro
-** increases its stack space ('L->ci->top.p').
-*/
-#define adjustresults(L,nres) \
- { if ((nres) <= LUA_MULTRET && L->ci->top.p < L->top.p) \
- L->ci->top.p = L->top.p; }
-
-
-/* Ensure the stack has at least 'n' elements */
-#define api_checknelems(L,n) \
- api_check(L, (n) < (L->top.p - L->ci->func.p), \
- "not enough elements in the stack")
-
-
-/* Ensure the stack has at least 'n' elements to be popped. (Some
-** functions only update a slot after checking it for popping, but that
-** is only an optimization for a pop followed by a push.)
-*/
-#define api_checkpop(L,n) \
- api_check(L, (n) < L->top.p - L->ci->func.p && \
- L->tbclist.p < L->top.p - (n), \
- "not enough free elements in the stack")
-
-#endif
diff --git a/lcode.c b/lcode.c
deleted file mode 100644
index 33cbd6874f..0000000000
--- a/lcode.c
+++ /dev/null
@@ -1,1972 +0,0 @@
-/*
-** $Id: lcode.c $
-** Code generator for Lua
-** See Copyright Notice in lua.h
-*/
-
-#define lcode_c
-#define LUA_CORE
-
-#include "lprefix.h"
-
-
-#include
-#include
-#include
-#include
-
-#include "lua.h"
-
-#include "lcode.h"
-#include "ldebug.h"
-#include "ldo.h"
-#include "lgc.h"
-#include "llex.h"
-#include "lmem.h"
-#include "lobject.h"
-#include "lopcodes.h"
-#include "lparser.h"
-#include "lstring.h"
-#include "ltable.h"
-#include "lvm.h"
-
-
-/* (note that expressions VJMP also have jumps.) */
-#define hasjumps(e) ((e)->t != (e)->f)
-
-
-static int codesJ (FuncState *fs, OpCode o, int sj, int k);
-
-
-
-/* semantic error */
-l_noret luaK_semerror (LexState *ls, const char *fmt, ...) {
- const char *msg;
- va_list argp;
- pushvfstring(ls->L, argp, fmt, msg);
- ls->t.token = 0; /* remove "near " from final message */
- ls->linenumber = ls->lastline; /* back to line of last used token */
- luaX_syntaxerror(ls, msg);
-}
-
-
-/*
-** If expression is a numeric constant, fills 'v' with its value
-** and returns 1. Otherwise, returns 0.
-*/
-static int tonumeral (const expdesc *e, TValue *v) {
- if (hasjumps(e))
- return 0; /* not a numeral */
- switch (e->k) {
- case VKINT:
- if (v) setivalue(v, e->u.ival);
- return 1;
- case VKFLT:
- if (v) setfltvalue(v, e->u.nval);
- return 1;
- default: return 0;
- }
-}
-
-
-/*
-** Get the constant value from a constant expression
-*/
-static TValue *const2val (FuncState *fs, const expdesc *e) {
- lua_assert(e->k == VCONST);
- return &fs->ls->dyd->actvar.arr[e->u.info].k;
-}
-
-
-/*
-** If expression is a constant, fills 'v' with its value
-** and returns 1. Otherwise, returns 0.
-*/
-int luaK_exp2const (FuncState *fs, const expdesc *e, TValue *v) {
- if (hasjumps(e))
- return 0; /* not a constant */
- switch (e->k) {
- case VFALSE:
- setbfvalue(v);
- return 1;
- case VTRUE:
- setbtvalue(v);
- return 1;
- case VNIL:
- setnilvalue(v);
- return 1;
- case VKSTR: {
- setsvalue(fs->ls->L, v, e->u.strval);
- return 1;
- }
- case VCONST: {
- setobj(fs->ls->L, v, const2val(fs, e));
- return 1;
- }
- default: return tonumeral(e, v);
- }
-}
-
-
-/*
-** Return the previous instruction of the current code. If there
-** may be a jump target between the current instruction and the
-** previous one, return an invalid instruction (to avoid wrong
-** optimizations).
-*/
-static Instruction *previousinstruction (FuncState *fs) {
- static const Instruction invalidinstruction = ~(Instruction)0;
- if (fs->pc > fs->lasttarget)
- return &fs->f->code[fs->pc - 1]; /* previous instruction */
- else
- return cast(Instruction*, &invalidinstruction);
-}
-
-
-/*
-** Create a OP_LOADNIL instruction, but try to optimize: if the previous
-** instruction is also OP_LOADNIL and ranges are compatible, adjust
-** range of previous instruction instead of emitting a new one. (For
-** instance, 'local a; local b' will generate a single opcode.)
-*/
-void luaK_nil (FuncState *fs, int from, int n) {
- int l = from + n - 1; /* last register to set nil */
- Instruction *previous = previousinstruction(fs);
- if (GET_OPCODE(*previous) == OP_LOADNIL) { /* previous is LOADNIL? */
- int pfrom = GETARG_A(*previous); /* get previous range */
- int pl = pfrom + GETARG_B(*previous);
- if ((pfrom <= from && from <= pl + 1) ||
- (from <= pfrom && pfrom <= l + 1)) { /* can connect both? */
- if (pfrom < from) from = pfrom; /* from = min(from, pfrom) */
- if (pl > l) l = pl; /* l = max(l, pl) */
- SETARG_A(*previous, from);
- SETARG_B(*previous, l - from);
- return;
- } /* else go through */
- }
- luaK_codeABC(fs, OP_LOADNIL, from, n - 1, 0); /* else no optimization */
-}
-
-
-/*
-** Gets the destination address of a jump instruction. Used to traverse
-** a list of jumps.
-*/
-static int getjump (FuncState *fs, int pc) {
- int offset = GETARG_sJ(fs->f->code[pc]);
- if (offset == NO_JUMP) /* point to itself represents end of list */
- return NO_JUMP; /* end of list */
- else
- return (pc+1)+offset; /* turn offset into absolute position */
-}
-
-
-/*
-** Fix jump instruction at position 'pc' to jump to 'dest'.
-** (Jump addresses are relative in Lua)
-*/
-static void fixjump (FuncState *fs, int pc, int dest) {
- Instruction *jmp = &fs->f->code[pc];
- int offset = dest - (pc + 1);
- lua_assert(dest != NO_JUMP);
- if (!(-OFFSET_sJ <= offset && offset <= MAXARG_sJ - OFFSET_sJ))
- luaX_syntaxerror(fs->ls, "control structure too long");
- lua_assert(GET_OPCODE(*jmp) == OP_JMP);
- SETARG_sJ(*jmp, offset);
-}
-
-
-/*
-** Concatenate jump-list 'l2' into jump-list 'l1'
-*/
-void luaK_concat (FuncState *fs, int *l1, int l2) {
- if (l2 == NO_JUMP) return; /* nothing to concatenate? */
- else if (*l1 == NO_JUMP) /* no original list? */
- *l1 = l2; /* 'l1' points to 'l2' */
- else {
- int list = *l1;
- int next;
- while ((next = getjump(fs, list)) != NO_JUMP) /* find last element */
- list = next;
- fixjump(fs, list, l2); /* last element links to 'l2' */
- }
-}
-
-
-/*
-** Create a jump instruction and return its position, so its destination
-** can be fixed later (with 'fixjump').
-*/
-int luaK_jump (FuncState *fs) {
- return codesJ(fs, OP_JMP, NO_JUMP, 0);
-}
-
-
-/*
-** Code a 'return' instruction
-*/
-void luaK_ret (FuncState *fs, int first, int nret) {
- OpCode op;
- switch (nret) {
- case 0: op = OP_RETURN0; break;
- case 1: op = OP_RETURN1; break;
- default: op = OP_RETURN; break;
- }
- luaY_checklimit(fs, nret + 1, MAXARG_B, "returns");
- luaK_codeABC(fs, op, first, nret + 1, 0);
-}
-
-
-/*
-** Code a "conditional jump", that is, a test or comparison opcode
-** followed by a jump. Return jump position.
-*/
-static int condjump (FuncState *fs, OpCode op, int A, int B, int C, int k) {
- luaK_codeABCk(fs, op, A, B, C, k);
- return luaK_jump(fs);
-}
-
-
-/*
-** returns current 'pc' and marks it as a jump target (to avoid wrong
-** optimizations with consecutive instructions not in the same basic block).
-*/
-int luaK_getlabel (FuncState *fs) {
- fs->lasttarget = fs->pc;
- return fs->pc;
-}
-
-
-/*
-** Returns the position of the instruction "controlling" a given
-** jump (that is, its condition), or the jump itself if it is
-** unconditional.
-*/
-static Instruction *getjumpcontrol (FuncState *fs, int pc) {
- Instruction *pi = &fs->f->code[pc];
- if (pc >= 1 && testTMode(GET_OPCODE(*(pi-1))))
- return pi-1;
- else
- return pi;
-}
-
-
-/*
-** Patch destination register for a TESTSET instruction.
-** If instruction in position 'node' is not a TESTSET, return 0 ("fails").
-** Otherwise, if 'reg' is not 'NO_REG', set it as the destination
-** register. Otherwise, change instruction to a simple 'TEST' (produces
-** no register value)
-*/
-static int patchtestreg (FuncState *fs, int node, int reg) {
- Instruction *i = getjumpcontrol(fs, node);
- if (GET_OPCODE(*i) != OP_TESTSET)
- return 0; /* cannot patch other instructions */
- if (reg != NO_REG && reg != GETARG_B(*i))
- SETARG_A(*i, reg);
- else {
- /* no register to put value or register already has the value;
- change instruction to simple test */
- *i = CREATE_ABCk(OP_TEST, GETARG_B(*i), 0, 0, GETARG_k(*i));
- }
- return 1;
-}
-
-
-/*
-** Traverse a list of tests ensuring no one produces a value
-*/
-static void removevalues (FuncState *fs, int list) {
- for (; list != NO_JUMP; list = getjump(fs, list))
- patchtestreg(fs, list, NO_REG);
-}
-
-
-/*
-** Traverse a list of tests, patching their destination address and
-** registers: tests producing values jump to 'vtarget' (and put their
-** values in 'reg'), other tests jump to 'dtarget'.
-*/
-static void patchlistaux (FuncState *fs, int list, int vtarget, int reg,
- int dtarget) {
- while (list != NO_JUMP) {
- int next = getjump(fs, list);
- if (patchtestreg(fs, list, reg))
- fixjump(fs, list, vtarget);
- else
- fixjump(fs, list, dtarget); /* jump to default target */
- list = next;
- }
-}
-
-
-/*
-** Path all jumps in 'list' to jump to 'target'.
-** (The assert means that we cannot fix a jump to a forward address
-** because we only know addresses once code is generated.)
-*/
-void luaK_patchlist (FuncState *fs, int list, int target) {
- lua_assert(target <= fs->pc);
- patchlistaux(fs, list, target, NO_REG, target);
-}
-
-
-void luaK_patchtohere (FuncState *fs, int list) {
- int hr = luaK_getlabel(fs); /* mark "here" as a jump target */
- luaK_patchlist(fs, list, hr);
-}
-
-
-/* limit for difference between lines in relative line info. */
-#define LIMLINEDIFF 0x80
-
-
-/*
-** Save line info for a new instruction. If difference from last line
-** does not fit in a byte, of after that many instructions, save a new
-** absolute line info; (in that case, the special value 'ABSLINEINFO'
-** in 'lineinfo' signals the existence of this absolute information.)
-** Otherwise, store the difference from last line in 'lineinfo'.
-*/
-static void savelineinfo (FuncState *fs, Proto *f, int line) {
- int linedif = line - fs->previousline;
- int pc = fs->pc - 1; /* last instruction coded */
- if (abs(linedif) >= LIMLINEDIFF || fs->iwthabs++ >= MAXIWTHABS) {
- luaM_growvector(fs->ls->L, f->abslineinfo, fs->nabslineinfo,
- f->sizeabslineinfo, AbsLineInfo, INT_MAX, "lines");
- f->abslineinfo[fs->nabslineinfo].pc = pc;
- f->abslineinfo[fs->nabslineinfo++].line = line;
- linedif = ABSLINEINFO; /* signal that there is absolute information */
- fs->iwthabs = 1; /* restart counter */
- }
- luaM_growvector(fs->ls->L, f->lineinfo, pc, f->sizelineinfo, ls_byte,
- INT_MAX, "opcodes");
- f->lineinfo[pc] = cast(ls_byte, linedif);
- fs->previousline = line; /* last line saved */
-}
-
-
-/*
-** Remove line information from the last instruction.
-** If line information for that instruction is absolute, set 'iwthabs'
-** above its max to force the new (replacing) instruction to have
-** absolute line info, too.
-*/
-static void removelastlineinfo (FuncState *fs) {
- Proto *f = fs->f;
- int pc = fs->pc - 1; /* last instruction coded */
- if (f->lineinfo[pc] != ABSLINEINFO) { /* relative line info? */
- fs->previousline -= f->lineinfo[pc]; /* correct last line saved */
- fs->iwthabs--; /* undo previous increment */
- }
- else { /* absolute line information */
- lua_assert(f->abslineinfo[fs->nabslineinfo - 1].pc == pc);
- fs->nabslineinfo--; /* remove it */
- fs->iwthabs = MAXIWTHABS + 1; /* force next line info to be absolute */
- }
-}
-
-
-/*
-** Remove the last instruction created, correcting line information
-** accordingly.
-*/
-static void removelastinstruction (FuncState *fs) {
- removelastlineinfo(fs);
- fs->pc--;
-}
-
-
-/*
-** Emit instruction 'i', checking for array sizes and saving also its
-** line information. Return 'i' position.
-*/
-int luaK_code (FuncState *fs, Instruction i) {
- Proto *f = fs->f;
- /* put new instruction in code array */
- luaM_growvector(fs->ls->L, f->code, fs->pc, f->sizecode, Instruction,
- INT_MAX, "opcodes");
- f->code[fs->pc++] = i;
- savelineinfo(fs, f, fs->ls->lastline);
- return fs->pc - 1; /* index of new instruction */
-}
-
-
-/*
-** Format and emit an 'iABC' instruction. (Assertions check consistency
-** of parameters versus opcode.)
-*/
-int luaK_codeABCk (FuncState *fs, OpCode o, int A, int B, int C, int k) {
- lua_assert(getOpMode(o) == iABC);
- lua_assert(A <= MAXARG_A && B <= MAXARG_B &&
- C <= MAXARG_C && (k & ~1) == 0);
- return luaK_code(fs, CREATE_ABCk(o, A, B, C, k));
-}
-
-
-int luaK_codevABCk (FuncState *fs, OpCode o, int A, int B, int C, int k) {
- lua_assert(getOpMode(o) == ivABC);
- lua_assert(A <= MAXARG_A && B <= MAXARG_vB &&
- C <= MAXARG_vC && (k & ~1) == 0);
- return luaK_code(fs, CREATE_vABCk(o, A, B, C, k));
-}
-
-
-/*
-** Format and emit an 'iABx' instruction.
-*/
-int luaK_codeABx (FuncState *fs, OpCode o, int A, int Bc) {
- lua_assert(getOpMode(o) == iABx);
- lua_assert(A <= MAXARG_A && Bc <= MAXARG_Bx);
- return luaK_code(fs, CREATE_ABx(o, A, Bc));
-}
-
-
-/*
-** Format and emit an 'iAsBx' instruction.
-*/
-static int codeAsBx (FuncState *fs, OpCode o, int A, int Bc) {
- int b = Bc + OFFSET_sBx;
- lua_assert(getOpMode(o) == iAsBx);
- lua_assert(A <= MAXARG_A && b <= MAXARG_Bx);
- return luaK_code(fs, CREATE_ABx(o, A, b));
-}
-
-
-/*
-** Format and emit an 'isJ' instruction.
-*/
-static int codesJ (FuncState *fs, OpCode o, int sj, int k) {
- int j = sj + OFFSET_sJ;
- lua_assert(getOpMode(o) == isJ);
- lua_assert(j <= MAXARG_sJ && (k & ~1) == 0);
- return luaK_code(fs, CREATE_sJ(o, j, k));
-}
-
-
-/*
-** Emit an "extra argument" instruction (format 'iAx')
-*/
-static int codeextraarg (FuncState *fs, int A) {
- lua_assert(A <= MAXARG_Ax);
- return luaK_code(fs, CREATE_Ax(OP_EXTRAARG, A));
-}
-
-
-/*
-** Emit a "load constant" instruction, using either 'OP_LOADK'
-** (if constant index 'k' fits in 18 bits) or an 'OP_LOADKX'
-** instruction with "extra argument".
-*/
-static int luaK_codek (FuncState *fs, int reg, int k) {
- if (k <= MAXARG_Bx)
- return luaK_codeABx(fs, OP_LOADK, reg, k);
- else {
- int p = luaK_codeABx(fs, OP_LOADKX, reg, 0);
- codeextraarg(fs, k);
- return p;
- }
-}
-
-
-/*
-** Check register-stack level, keeping track of its maximum size
-** in field 'maxstacksize'
-*/
-void luaK_checkstack (FuncState *fs, int n) {
- int newstack = fs->freereg + n;
- if (newstack > fs->f->maxstacksize) {
- luaY_checklimit(fs, newstack, MAX_FSTACK, "registers");
- fs->f->maxstacksize = cast_byte(newstack);
- }
-}
-
-
-/*
-** Reserve 'n' registers in register stack
-*/
-void luaK_reserveregs (FuncState *fs, int n) {
- luaK_checkstack(fs, n);
- fs->freereg = cast_byte(fs->freereg + n);
-}
-
-
-/*
-** Free register 'reg', if it is neither a constant index nor
-** a local variable.
-)
-*/
-static void freereg (FuncState *fs, int reg) {
- if (reg >= luaY_nvarstack(fs)) {
- fs->freereg--;
- lua_assert(reg == fs->freereg);
- }
-}
-
-
-/*
-** Free two registers in proper order
-*/
-static void freeregs (FuncState *fs, int r1, int r2) {
- if (r1 > r2) {
- freereg(fs, r1);
- freereg(fs, r2);
- }
- else {
- freereg(fs, r2);
- freereg(fs, r1);
- }
-}
-
-
-/*
-** Free register used by expression 'e' (if any)
-*/
-static void freeexp (FuncState *fs, expdesc *e) {
- if (e->k == VNONRELOC)
- freereg(fs, e->u.info);
-}
-
-
-/*
-** Free registers used by expressions 'e1' and 'e2' (if any) in proper
-** order.
-*/
-static void freeexps (FuncState *fs, expdesc *e1, expdesc *e2) {
- int r1 = (e1->k == VNONRELOC) ? e1->u.info : -1;
- int r2 = (e2->k == VNONRELOC) ? e2->u.info : -1;
- freeregs(fs, r1, r2);
-}
-
-
-/*
-** Add constant 'v' to prototype's list of constants (field 'k').
-*/
-static int addk (FuncState *fs, Proto *f, TValue *v) {
- lua_State *L = fs->ls->L;
- int oldsize = f->sizek;
- int k = fs->nk;
- luaM_growvector(L, f->k, k, f->sizek, TValue, MAXARG_Ax, "constants");
- while (oldsize < f->sizek)
- setnilvalue(&f->k[oldsize++]);
- setobj(L, &f->k[k], v);
- fs->nk++;
- luaC_barrier(L, f, v);
- return k;
-}
-
-
-/*
-** Use scanner's table to cache position of constants in constant list
-** and try to reuse constants. Because some values should not be used
-** as keys (nil cannot be a key, integer keys can collapse with float
-** keys), the caller must provide a useful 'key' for indexing the cache.
-*/
-static int k2proto (FuncState *fs, TValue *key, TValue *v) {
- TValue val;
- Proto *f = fs->f;
- int tag = luaH_get(fs->kcache, key, &val); /* query scanner table */
- if (!tagisempty(tag)) { /* is there an index there? */
- int k = cast_int(ivalue(&val));
- /* collisions can happen only for float keys */
- lua_assert(ttisfloat(key) || luaV_rawequalobj(&f->k[k], v));
- return k; /* reuse index */
- }
- else { /* constant not found; create a new entry */
- int k = addk(fs, f, v);
- /* cache it for reuse; numerical value does not need GC barrier;
- table is not a metatable, so it does not need to invalidate cache */
- setivalue(&val, k);
- luaH_set(fs->ls->L, fs->kcache, key, &val);
- return k;
- }
-}
-
-
-/*
-** Add a string to list of constants and return its index.
-*/
-static int stringK (FuncState *fs, TString *s) {
- TValue o;
- setsvalue(fs->ls->L, &o, s);
- return k2proto(fs, &o, &o); /* use string itself as key */
-}
-
-
-/*
-** Add an integer to list of constants and return its index.
-*/
-static int luaK_intK (FuncState *fs, lua_Integer n) {
- TValue o;
- setivalue(&o, n);
- return k2proto(fs, &o, &o); /* use integer itself as key */
-}
-
-/*
-** Add a float to list of constants and return its index. Floats
-** with integral values need a different key, to avoid collision
-** with actual integers. To that end, we add to the number its smaller
-** power-of-two fraction that is still significant in its scale.
-** (For doubles, the fraction would be 2^-52).
-** This method is not bulletproof: different numbers may generate the
-** same key (e.g., very large numbers will overflow to 'inf') and for
-** floats larger than 2^53 the result is still an integer. For those
-** cases, just generate a new entry. At worst, this only wastes an entry
-** with a duplicate.
-*/
-static int luaK_numberK (FuncState *fs, lua_Number r) {
- TValue o, kv;
- setfltvalue(&o, r); /* value as a TValue */
- if (r == 0) { /* handle zero as a special case */
- setpvalue(&kv, fs); /* use FuncState as index */
- return k2proto(fs, &kv, &o); /* cannot collide */
- }
- else {
- const int nbm = l_floatatt(MANT_DIG);
- const lua_Number q = l_mathop(ldexp)(l_mathop(1.0), -nbm + 1);
- const lua_Number k = r * (1 + q); /* key */
- lua_Integer ik;
- setfltvalue(&kv, k); /* key as a TValue */
- if (!luaV_flttointeger(k, &ik, F2Ieq)) { /* not an integer value? */
- int n = k2proto(fs, &kv, &o); /* use key */
- if (luaV_rawequalobj(&fs->f->k[n], &o)) /* correct value? */
- return n;
- }
- /* else, either key is still an integer or there was a collision;
- anyway, do not try to reuse constant; instead, create a new one */
- return addk(fs, fs->f, &o);
- }
-}
-
-
-/*
-** Add a false to list of constants and return its index.
-*/
-static int boolF (FuncState *fs) {
- TValue o;
- setbfvalue(&o);
- return k2proto(fs, &o, &o); /* use boolean itself as key */
-}
-
-
-/*
-** Add a true to list of constants and return its index.
-*/
-static int boolT (FuncState *fs) {
- TValue o;
- setbtvalue(&o);
- return k2proto(fs, &o, &o); /* use boolean itself as key */
-}
-
-
-/*
-** Add nil to list of constants and return its index.
-*/
-static int nilK (FuncState *fs) {
- TValue k, v;
- setnilvalue(&v);
- /* cannot use nil as key; instead use table itself */
- sethvalue(fs->ls->L, &k, fs->kcache);
- return k2proto(fs, &k, &v);
-}
-
-
-/*
-** Check whether 'i' can be stored in an 'sC' operand. Equivalent to
-** (0 <= int2sC(i) && int2sC(i) <= MAXARG_C) but without risk of
-** overflows in the hidden addition inside 'int2sC'.
-*/
-static int fitsC (lua_Integer i) {
- return (l_castS2U(i) + OFFSET_sC <= cast_uint(MAXARG_C));
-}
-
-
-/*
-** Check whether 'i' can be stored in an 'sBx' operand.
-*/
-static int fitsBx (lua_Integer i) {
- return (-OFFSET_sBx <= i && i <= MAXARG_Bx - OFFSET_sBx);
-}
-
-
-void luaK_int (FuncState *fs, int reg, lua_Integer i) {
- if (fitsBx(i))
- codeAsBx(fs, OP_LOADI, reg, cast_int(i));
- else
- luaK_codek(fs, reg, luaK_intK(fs, i));
-}
-
-
-static void luaK_float (FuncState *fs, int reg, lua_Number f) {
- lua_Integer fi;
- if (luaV_flttointeger(f, &fi, F2Ieq) && fitsBx(fi))
- codeAsBx(fs, OP_LOADF, reg, cast_int(fi));
- else
- luaK_codek(fs, reg, luaK_numberK(fs, f));
-}
-
-
-/*
-** Get the value of 'var' in a register and generate an opcode to check
-** whether that register is nil. 'k' is the index of the variable name
-** in the list of constants. If its value cannot be encoded in Bx, a 0
-** will use '?' for the name.
-*/
-void luaK_codecheckglobal (FuncState *fs, expdesc *var, int k, int line) {
- luaK_exp2anyreg(fs, var);
- luaK_fixline(fs, line);
- k = (k >= MAXARG_Bx) ? 0 : k + 1;
- luaK_codeABx(fs, OP_ERRNNIL, var->u.info, k);
- luaK_fixline(fs, line);
- freeexp(fs, var);
-}
-
-
-/*
-** Convert a constant in 'v' into an expression description 'e'
-*/
-static void const2exp (TValue *v, expdesc *e) {
- switch (ttypetag(v)) {
- case LUA_VNUMINT:
- e->k = VKINT; e->u.ival = ivalue(v);
- break;
- case LUA_VNUMFLT:
- e->k = VKFLT; e->u.nval = fltvalue(v);
- break;
- case LUA_VFALSE:
- e->k = VFALSE;
- break;
- case LUA_VTRUE:
- e->k = VTRUE;
- break;
- case LUA_VNIL:
- e->k = VNIL;
- break;
- case LUA_VSHRSTR: case LUA_VLNGSTR:
- e->k = VKSTR; e->u.strval = tsvalue(v);
- break;
- default: lua_assert(0);
- }
-}
-
-
-/*
-** Fix an expression to return the number of results 'nresults'.
-** 'e' must be a multi-ret expression (function call or vararg).
-*/
-void luaK_setreturns (FuncState *fs, expdesc *e, int nresults) {
- Instruction *pc = &getinstruction(fs, e);
- luaY_checklimit(fs, nresults + 1, MAXARG_C, "multiple results");
- if (e->k == VCALL) /* expression is an open function call? */
- SETARG_C(*pc, nresults + 1);
- else {
- lua_assert(e->k == VVARARG);
- SETARG_C(*pc, nresults + 1);
- SETARG_A(*pc, fs->freereg);
- luaK_reserveregs(fs, 1);
- }
-}
-
-
-/*
-** Convert a VKSTR to a VK
-*/
-static int str2K (FuncState *fs, expdesc *e) {
- lua_assert(e->k == VKSTR);
- e->u.info = stringK(fs, e->u.strval);
- e->k = VK;
- return e->u.info;
-}
-
-
-/*
-** Fix an expression to return one result.
-** If expression is not a multi-ret expression (function call or
-** vararg), it already returns one result, so nothing needs to be done.
-** Function calls become VNONRELOC expressions (as its result comes
-** fixed in the base register of the call), while vararg expressions
-** become VRELOC (as OP_VARARG puts its results where it wants).
-** (Calls are created returning one result, so that does not need
-** to be fixed.)
-*/
-void luaK_setoneret (FuncState *fs, expdesc *e) {
- if (e->k == VCALL) { /* expression is an open function call? */
- /* already returns 1 value */
- lua_assert(GETARG_C(getinstruction(fs, e)) == 2);
- e->k = VNONRELOC; /* result has fixed position */
- e->u.info = GETARG_A(getinstruction(fs, e));
- }
- else if (e->k == VVARARG) {
- SETARG_C(getinstruction(fs, e), 2);
- e->k = VRELOC; /* can relocate its simple result */
- }
-}
-
-/*
-** Change a vararg parameter into a regular local variable
-*/
-void luaK_vapar2local (FuncState *fs, expdesc *var) {
- needvatab(fs->f); /* function will need a vararg table */
- /* now a vararg parameter is equivalent to a regular local variable */
- var->k = VLOCAL;
-}
-
-
-/*
-** Ensure that expression 'e' is not a variable (nor a ).
-** (Expression still may have jump lists.)
-*/
-void luaK_dischargevars (FuncState *fs, expdesc *e) {
- switch (e->k) {
- case VCONST: {
- const2exp(const2val(fs, e), e);
- break;
- }
- case VVARGVAR: {
- luaK_vapar2local(fs, e); /* turn it into a local variable */
- } /* FALLTHROUGH */
- case VLOCAL: { /* already in a register */
- int temp = e->u.var.ridx;
- e->u.info = temp; /* (avoid a direct assignment; values overlap) */
- e->k = VNONRELOC; /* becomes a non-relocatable value */
- break;
- }
- case VUPVAL: { /* move value to some (pending) register */
- e->u.info = luaK_codeABC(fs, OP_GETUPVAL, 0, e->u.info, 0);
- e->k = VRELOC;
- break;
- }
- case VINDEXUP: {
- e->u.info = luaK_codeABC(fs, OP_GETTABUP, 0, e->u.ind.t, e->u.ind.idx);
- e->k = VRELOC;
- break;
- }
- case VINDEXI: {
- freereg(fs, e->u.ind.t);
- e->u.info = luaK_codeABC(fs, OP_GETI, 0, e->u.ind.t, e->u.ind.idx);
- e->k = VRELOC;
- break;
- }
- case VINDEXSTR: {
- freereg(fs, e->u.ind.t);
- e->u.info = luaK_codeABC(fs, OP_GETFIELD, 0, e->u.ind.t, e->u.ind.idx);
- e->k = VRELOC;
- break;
- }
- case VINDEXED: {
- freeregs(fs, e->u.ind.t, e->u.ind.idx);
- e->u.info = luaK_codeABC(fs, OP_GETTABLE, 0, e->u.ind.t, e->u.ind.idx);
- e->k = VRELOC;
- break;
- }
- case VVARGIND: {
- freeregs(fs, e->u.ind.t, e->u.ind.idx);
- e->u.info = luaK_codeABC(fs, OP_GETVARG, 0, e->u.ind.t, e->u.ind.idx);
- e->k = VRELOC;
- break;
- }
- case VVARARG: case VCALL: {
- luaK_setoneret(fs, e);
- break;
- }
- default: break; /* there is one value available (somewhere) */
- }
-}
-
-
-/*
-** Ensure expression value is in register 'reg', making 'e' a
-** non-relocatable expression.
-** (Expression still may have jump lists.)
-*/
-static void discharge2reg (FuncState *fs, expdesc *e, int reg) {
- luaK_dischargevars(fs, e);
- switch (e->k) {
- case VNIL: {
- luaK_nil(fs, reg, 1);
- break;
- }
- case VFALSE: {
- luaK_codeABC(fs, OP_LOADFALSE, reg, 0, 0);
- break;
- }
- case VTRUE: {
- luaK_codeABC(fs, OP_LOADTRUE, reg, 0, 0);
- break;
- }
- case VKSTR: {
- str2K(fs, e);
- } /* FALLTHROUGH */
- case VK: {
- luaK_codek(fs, reg, e->u.info);
- break;
- }
- case VKFLT: {
- luaK_float(fs, reg, e->u.nval);
- break;
- }
- case VKINT: {
- luaK_int(fs, reg, e->u.ival);
- break;
- }
- case VRELOC: {
- Instruction *pc = &getinstruction(fs, e);
- SETARG_A(*pc, reg); /* instruction will put result in 'reg' */
- break;
- }
- case VNONRELOC: {
- if (reg != e->u.info)
- luaK_codeABC(fs, OP_MOVE, reg, e->u.info, 0);
- break;
- }
- default: {
- lua_assert(e->k == VJMP);
- return; /* nothing to do... */
- }
- }
- e->u.info = reg;
- e->k = VNONRELOC;
-}
-
-
-/*
-** Ensure expression value is in a register, making 'e' a
-** non-relocatable expression.
-** (Expression still may have jump lists.)
-*/
-static void discharge2anyreg (FuncState *fs, expdesc *e) {
- if (e->k != VNONRELOC) { /* no fixed register yet? */
- luaK_reserveregs(fs, 1); /* get a register */
- discharge2reg(fs, e, fs->freereg-1); /* put value there */
- }
-}
-
-
-static int code_loadbool (FuncState *fs, int A, OpCode op) {
- luaK_getlabel(fs); /* those instructions may be jump targets */
- return luaK_codeABC(fs, op, A, 0, 0);
-}
-
-
-/*
-** 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) {
- for (; list != NO_JUMP; list = getjump(fs, list)) {
- Instruction i = *getjumpcontrol(fs, list);
- if (GET_OPCODE(i) != OP_TESTSET) return 1;
- }
- return 0; /* not found */
-}
-
-
-/*
-** Ensures final expression result (which includes results from its
-** jump lists) is in register 'reg'.
-** If expression has jumps, need to patch these jumps either to
-** its final position or to "load" instructions (for those tests
-** that do not produce values).
-*/
-static void exp2reg (FuncState *fs, expdesc *e, int reg) {
- discharge2reg(fs, e, reg);
- if (e->k == VJMP) /* expression itself is a test? */
- luaK_concat(fs, &e->t, e->u.info); /* put this jump in 't' list */
- if (hasjumps(e)) {
- 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) || need_value(fs, e->f)) {
- int fj = (e->k == VJMP) ? NO_JUMP : luaK_jump(fs);
- p_f = code_loadbool(fs, reg, OP_LFALSESKIP); /* skip next inst. */
- p_t = code_loadbool(fs, reg, OP_LOADTRUE);
- /* jump around these booleans if 'e' is not a test */
- luaK_patchtohere(fs, fj);
- }
- final = luaK_getlabel(fs);
- patchlistaux(fs, e->f, final, reg, p_f);
- patchlistaux(fs, e->t, final, reg, p_t);
- }
- e->f = e->t = NO_JUMP;
- e->u.info = reg;
- e->k = VNONRELOC;
-}
-
-
-/*
-** Ensures final expression result is in next available register.
-*/
-void luaK_exp2nextreg (FuncState *fs, expdesc *e) {
- luaK_dischargevars(fs, e);
- freeexp(fs, e);
- luaK_reserveregs(fs, 1);
- exp2reg(fs, e, fs->freereg - 1);
-}
-
-
-/*
-** Ensures final expression result is in some (any) register
-** and return that register.
-*/
-int luaK_exp2anyreg (FuncState *fs, expdesc *e) {
- luaK_dischargevars(fs, e);
- if (e->k == VNONRELOC) { /* expression already has a register? */
- if (!hasjumps(e)) /* no jumps? */
- return e->u.info; /* result is already in a register */
- if (e->u.info >= luaY_nvarstack(fs)) { /* reg. is not a local? */
- exp2reg(fs, e, e->u.info); /* put final result in it */
- return e->u.info;
- }
- /* else expression has jumps and cannot change its register
- to hold the jump values, because it is a local variable.
- Go through to the default case. */
- }
- luaK_exp2nextreg(fs, e); /* default: use next available register */
- return e->u.info;
-}
-
-
-/*
-** Ensures final expression result is either in a register,
-** in an upvalue, or it is the vararg parameter.
-*/
-void luaK_exp2anyregup (FuncState *fs, expdesc *e) {
- if ((e->k != VUPVAL && e->k != VVARGVAR) || hasjumps(e))
- luaK_exp2anyreg(fs, e);
-}
-
-
-/*
-** Ensures final expression result is either in a register
-** or it is a constant.
-*/
-void luaK_exp2val (FuncState *fs, expdesc *e) {
- if (e->k == VJMP || hasjumps(e))
- luaK_exp2anyreg(fs, e);
- else
- luaK_dischargevars(fs, e);
-}
-
-
-/*
-** Try to make 'e' a K expression with an index in the range of R/K
-** indices. Return true iff succeeded.
-*/
-static int luaK_exp2K (FuncState *fs, expdesc *e) {
- if (!hasjumps(e)) {
- int info;
- switch (e->k) { /* move constants to 'k' */
- case VTRUE: info = boolT(fs); break;
- case VFALSE: info = boolF(fs); break;
- case VNIL: info = nilK(fs); break;
- case VKINT: info = luaK_intK(fs, e->u.ival); break;
- case VKFLT: info = luaK_numberK(fs, e->u.nval); break;
- case VKSTR: info = stringK(fs, e->u.strval); break;
- case VK: info = e->u.info; break;
- default: return 0; /* not a constant */
- }
- if (info <= MAXINDEXRK) { /* does constant fit in 'argC'? */
- e->k = VK; /* make expression a 'K' expression */
- e->u.info = info;
- return 1;
- }
- }
- /* else, expression doesn't fit; leave it unchanged */
- return 0;
-}
-
-
-/*
-** Ensures final expression result is in a valid R/K index
-** (that is, it is either in a register or in 'k' with an index
-** in the range of R/K indices).
-** Returns 1 iff expression is K.
-*/
-static int exp2RK (FuncState *fs, expdesc *e) {
- if (luaK_exp2K(fs, e))
- return 1;
- else { /* not a constant in the right range: put it in a register */
- luaK_exp2anyreg(fs, e);
- return 0;
- }
-}
-
-
-static void codeABRK (FuncState *fs, OpCode o, int A, int B,
- expdesc *ec) {
- int k = exp2RK(fs, ec);
- luaK_codeABCk(fs, o, A, B, ec->u.info, k);
-}
-
-
-/*
-** Generate code to store result of expression 'ex' into variable 'var'.
-*/
-void luaK_storevar (FuncState *fs, expdesc *var, expdesc *ex) {
- switch (var->k) {
- case VLOCAL: {
- freeexp(fs, ex);
- exp2reg(fs, ex, var->u.var.ridx); /* compute 'ex' into proper place */
- return;
- }
- case VUPVAL: {
- int e = luaK_exp2anyreg(fs, ex);
- luaK_codeABC(fs, OP_SETUPVAL, e, var->u.info, 0);
- break;
- }
- case VINDEXUP: {
- codeABRK(fs, OP_SETTABUP, var->u.ind.t, var->u.ind.idx, ex);
- break;
- }
- case VINDEXI: {
- codeABRK(fs, OP_SETI, var->u.ind.t, var->u.ind.idx, ex);
- break;
- }
- case VINDEXSTR: {
- codeABRK(fs, OP_SETFIELD, var->u.ind.t, var->u.ind.idx, ex);
- break;
- }
- case VVARGIND: {
- needvatab(fs->f); /* function will need a vararg table */
- /* now, assignment is to a regular table */
- } /* FALLTHROUGH */
- case VINDEXED: {
- codeABRK(fs, OP_SETTABLE, var->u.ind.t, var->u.ind.idx, ex);
- break;
- }
- default: lua_assert(0); /* invalid var kind to store */
- }
- freeexp(fs, ex);
-}
-
-
-/*
-** Negate condition 'e' (where 'e' is a comparison).
-*/
-static void negatecondition (FuncState *fs, expdesc *e) {
- Instruction *pc = getjumpcontrol(fs, e->u.info);
- lua_assert(testTMode(GET_OPCODE(*pc)) && GET_OPCODE(*pc) != OP_TESTSET &&
- GET_OPCODE(*pc) != OP_TEST);
- SETARG_k(*pc, (GETARG_k(*pc) ^ 1));
-}
-
-
-/*
-** Emit instruction to jump if 'e' is 'cond' (that is, if 'cond'
-** is true, code will jump if 'e' is true.) Return jump position.
-** Optimize when 'e' is 'not' something, inverting the condition
-** and removing the 'not'.
-*/
-static int jumponcond (FuncState *fs, expdesc *e, int cond) {
- if (e->k == VRELOC) {
- Instruction ie = getinstruction(fs, e);
- if (GET_OPCODE(ie) == OP_NOT) {
- removelastinstruction(fs); /* remove previous OP_NOT */
- return condjump(fs, OP_TEST, GETARG_B(ie), 0, 0, !cond);
- }
- /* else go through */
- }
- discharge2anyreg(fs, e);
- freeexp(fs, e);
- return condjump(fs, OP_TESTSET, NO_REG, e->u.info, 0, cond);
-}
-
-
-/*
-** Emit code to go through if 'e' is true, jump otherwise.
-*/
-void luaK_goiftrue (FuncState *fs, expdesc *e) {
- int pc; /* pc of new jump */
- luaK_dischargevars(fs, e);
- switch (e->k) {
- case VJMP: { /* condition? */
- negatecondition(fs, e); /* jump when it is false */
- pc = e->u.info; /* save jump position */
- break;
- }
- case VK: case VKFLT: case VKINT: case VKSTR: case VTRUE: {
- pc = NO_JUMP; /* always true; do nothing */
- break;
- }
- default: {
- pc = jumponcond(fs, e, 0); /* jump when false */
- break;
- }
- }
- luaK_concat(fs, &e->f, pc); /* insert new jump in false list */
- luaK_patchtohere(fs, e->t); /* true list jumps to here (to go through) */
- e->t = NO_JUMP;
-}
-
-
-/*
-** Emit code to go through if 'e' is false, jump otherwise.
-*/
-static void luaK_goiffalse (FuncState *fs, expdesc *e) {
- int pc; /* pc of new jump */
- luaK_dischargevars(fs, e);
- switch (e->k) {
- case VJMP: {
- pc = e->u.info; /* already jump if true */
- break;
- }
- case VNIL: case VFALSE: {
- pc = NO_JUMP; /* always false; do nothing */
- break;
- }
- default: {
- pc = jumponcond(fs, e, 1); /* jump if true */
- break;
- }
- }
- luaK_concat(fs, &e->t, pc); /* insert new jump in 't' list */
- luaK_patchtohere(fs, e->f); /* false list jumps to here (to go through) */
- e->f = NO_JUMP;
-}
-
-
-/*
-** Code 'not e', doing constant folding.
-*/
-static void codenot (FuncState *fs, expdesc *e) {
- switch (e->k) {
- case VNIL: case VFALSE: {
- e->k = VTRUE; /* true == not nil == not false */
- break;
- }
- case VK: case VKFLT: case VKINT: case VKSTR: case VTRUE: {
- e->k = VFALSE; /* false == not "x" == not 0.5 == not 1 == not true */
- break;
- }
- case VJMP: {
- negatecondition(fs, e);
- break;
- }
- case VRELOC:
- case VNONRELOC: {
- discharge2anyreg(fs, e);
- freeexp(fs, e);
- e->u.info = luaK_codeABC(fs, OP_NOT, 0, e->u.info, 0);
- e->k = VRELOC;
- break;
- }
- default: lua_assert(0); /* cannot happen */
- }
- /* interchange true and false lists */
- { int temp = e->f; e->f = e->t; e->t = temp; }
- removevalues(fs, e->f); /* values are useless when negated */
- removevalues(fs, e->t);
-}
-
-
-/*
-** Check whether expression 'e' is a short literal string
-*/
-static int isKstr (FuncState *fs, expdesc *e) {
- return (e->k == VK && !hasjumps(e) && e->u.info <= MAXINDEXRK &&
- ttisshrstring(&fs->f->k[e->u.info]));
-}
-
-/*
-** Check whether expression 'e' is a literal integer.
-*/
-static int isKint (expdesc *e) {
- return (e->k == VKINT && !hasjumps(e));
-}
-
-
-/*
-** Check whether expression 'e' is a literal integer in
-** proper range to fit in register C
-*/
-static int isCint (expdesc *e) {
- return isKint(e) && (l_castS2U(e->u.ival) <= l_castS2U(MAXARG_C));
-}
-
-
-/*
-** Check whether expression 'e' is a literal integer in
-** proper range to fit in register sC
-*/
-static int isSCint (expdesc *e) {
- return isKint(e) && fitsC(e->u.ival);
-}
-
-
-/*
-** Check whether expression 'e' is a literal integer or float in
-** proper range to fit in a register (sB or sC).
-*/
-static int isSCnumber (expdesc *e, int *pi, int *isfloat) {
- lua_Integer i;
- if (e->k == VKINT)
- i = e->u.ival;
- else if (e->k == VKFLT && luaV_flttointeger(e->u.nval, &i, F2Ieq))
- *isfloat = 1;
- else
- return 0; /* not a number */
- if (!hasjumps(e) && fitsC(i)) {
- *pi = int2sC(cast_int(i));
- return 1;
- }
- else
- return 0;
-}
-
-
-/*
-** Emit SELF instruction or equivalent: the code will convert
-** expression 'e' into 'e.key(e,'.
-*/
-void luaK_self (FuncState *fs, expdesc *e, expdesc *key) {
- int ereg, base;
- luaK_exp2anyreg(fs, e);
- ereg = e->u.info; /* register where 'e' (the receiver) was placed */
- freeexp(fs, e);
- base = e->u.info = fs->freereg; /* base register for op_self */
- e->k = VNONRELOC; /* self expression has a fixed register */
- luaK_reserveregs(fs, 2); /* method and 'self' produced by op_self */
- lua_assert(key->k == VKSTR);
- /* is method name a short string in a valid K index? */
- if (strisshr(key->u.strval) && luaK_exp2K(fs, key)) {
- /* can use 'self' opcode */
- luaK_codeABCk(fs, OP_SELF, base, ereg, key->u.info, 0);
- }
- else { /* cannot use 'self' opcode; use move+gettable */
- luaK_exp2anyreg(fs, key); /* put method name in a register */
- luaK_codeABC(fs, OP_MOVE, base + 1, ereg, 0); /* copy self to base+1 */
- luaK_codeABC(fs, OP_GETTABLE, base, ereg, key->u.info); /* get method */
- }
- freeexp(fs, key);
-}
-
-
-/* auxiliary function to define indexing expressions */
-static void fillidxk (expdesc *t, int idx, expkind k) {
- t->u.ind.idx = cast_byte(idx);
- t->k = k;
-}
-
-
-/*
-** Create expression 't[k]'. 't' must have its final result already in a
-** register or upvalue. Upvalues can only be indexed by literal strings.
-** Keys can be literal strings in the constant table or arbitrary
-** values in registers.
-*/
-void luaK_indexed (FuncState *fs, expdesc *t, expdesc *k) {
- int keystr = -1;
- if (k->k == VKSTR)
- keystr = str2K(fs, k);
- lua_assert(!hasjumps(t) &&
- (t->k == VLOCAL || t->k == VVARGVAR ||
- t->k == VNONRELOC || t->k == VUPVAL));
- if (t->k == VUPVAL && !isKstr(fs, k)) /* upvalue indexed by non 'Kstr'? */
- luaK_exp2anyreg(fs, t); /* put it in a register */
- if (t->k == VUPVAL) {
- lu_byte temp = cast_byte(t->u.info); /* upvalue index */
- t->u.ind.t = temp; /* (avoid a direct assignment; values overlap) */
- lua_assert(isKstr(fs, k));
- fillidxk(t, k->u.info, VINDEXUP); /* literal short string */
- }
- else if (t->k == VVARGVAR) { /* indexing the vararg parameter? */
- int kreg = luaK_exp2anyreg(fs, k); /* put key in some register */
- lu_byte vreg = cast_byte(t->u.var.ridx); /* register with vararg param. */
- lua_assert(vreg == fs->f->numparams);
- t->u.ind.t = vreg; /* (avoid a direct assignment; values may overlap?) */
- fillidxk(t, kreg, VVARGIND); /* 't' represents 'vararg[k]' */
- }
- else {
- /* register index of the table */
- lu_byte temp = cast_byte((t->k == VLOCAL) ? t->u.var.ridx: t->u.info);
- t->u.ind.t = temp; /* (avoid a direct assignment; values may overlap?) */
- if (isKstr(fs, k))
- fillidxk(t, k->u.info, VINDEXSTR); /* literal short string */
- else if (isCint(k)) /* int. constant in proper range? */
- fillidxk(t, cast_int(k->u.ival), VINDEXI);
- else
- fillidxk(t, luaK_exp2anyreg(fs, k), VINDEXED); /* register */
- }
- t->u.ind.keystr = keystr; /* string index in 'k' */
- t->u.ind.ro = 0; /* by default, not read-only */
-}
-
-
-/*
-** Return false if folding can raise an error.
-** Bitwise operations need operands convertible to integers; division
-** operations cannot have 0 as divisor.
-*/
-static int validop (int op, TValue *v1, TValue *v2) {
- switch (op) {
- case LUA_OPBAND: case LUA_OPBOR: case LUA_OPBXOR:
- case LUA_OPSHL: case LUA_OPSHR: case LUA_OPBNOT: { /* conversion errors */
- lua_Integer i;
- return (luaV_tointegerns(v1, &i, LUA_FLOORN2I) &&
- luaV_tointegerns(v2, &i, LUA_FLOORN2I));
- }
- case LUA_OPDIV: case LUA_OPIDIV: case LUA_OPMOD: /* division by 0 */
- return (nvalue(v2) != 0);
- default: return 1; /* everything else is valid */
- }
-}
-
-
-/*
-** Try to "constant-fold" an operation; return 1 iff successful.
-** (In this case, 'e1' has the final result.)
-*/
-static int constfolding (FuncState *fs, int op, expdesc *e1,
- const expdesc *e2) {
- TValue v1, v2, res;
- if (!tonumeral(e1, &v1) || !tonumeral(e2, &v2) || !validop(op, &v1, &v2))
- return 0; /* non-numeric operands or not safe to fold */
- luaO_rawarith(fs->ls->L, op, &v1, &v2, &res); /* does operation */
- if (ttisinteger(&res)) {
- e1->k = VKINT;
- e1->u.ival = ivalue(&res);
- }
- else { /* folds neither NaN nor 0.0 (to avoid problems with -0.0) */
- lua_Number n = fltvalue(&res);
- if (luai_numisnan(n) || n == 0)
- return 0;
- e1->k = VKFLT;
- e1->u.nval = n;
- }
- return 1;
-}
-
-
-/*
-** Convert a BinOpr to an OpCode (ORDER OPR - ORDER OP)
-*/
-l_sinline OpCode binopr2op (BinOpr opr, BinOpr baser, OpCode base) {
- lua_assert(baser <= opr &&
- ((baser == OPR_ADD && opr <= OPR_SHR) ||
- (baser == OPR_LT && opr <= OPR_LE)));
- return cast(OpCode, (cast_int(opr) - cast_int(baser)) + cast_int(base));
-}
-
-
-/*
-** Convert a UnOpr to an OpCode (ORDER OPR - ORDER OP)
-*/
-l_sinline OpCode unopr2op (UnOpr opr) {
- return cast(OpCode, (cast_int(opr) - cast_int(OPR_MINUS)) +
- cast_int(OP_UNM));
-}
-
-
-/*
-** Convert a BinOpr to a tag method (ORDER OPR - ORDER TM)
-*/
-l_sinline TMS binopr2TM (BinOpr opr) {
- lua_assert(OPR_ADD <= opr && opr <= OPR_SHR);
- return cast(TMS, (cast_int(opr) - cast_int(OPR_ADD)) + cast_int(TM_ADD));
-}
-
-
-/*
-** Emit code for unary expressions that "produce values"
-** (everything but 'not').
-** Expression to produce final result will be encoded in 'e'.
-*/
-static void codeunexpval (FuncState *fs, OpCode op, expdesc *e, int line) {
- int r = luaK_exp2anyreg(fs, e); /* opcodes operate only on registers */
- freeexp(fs, e);
- e->u.info = luaK_codeABC(fs, op, 0, r, 0); /* generate opcode */
- e->k = VRELOC; /* all those operations are relocatable */
- luaK_fixline(fs, line);
-}
-
-
-/*
-** Emit code for binary expressions that "produce values"
-** (everything but logical operators 'and'/'or' and comparison
-** operators).
-** Expression to produce final result will be encoded in 'e1'.
-*/
-static void finishbinexpval (FuncState *fs, expdesc *e1, expdesc *e2,
- OpCode op, int v2, int flip, int line,
- OpCode mmop, TMS event) {
- int v1 = luaK_exp2anyreg(fs, e1);
- int pc = luaK_codeABCk(fs, op, 0, v1, v2, 0);
- freeexps(fs, e1, e2);
- e1->u.info = pc;
- e1->k = VRELOC; /* all those operations are relocatable */
- luaK_fixline(fs, line);
- luaK_codeABCk(fs, mmop, v1, v2, cast_int(event), flip); /* metamethod */
- luaK_fixline(fs, line);
-}
-
-
-/*
-** Emit code for binary expressions that "produce values" over
-** two registers.
-*/
-static void codebinexpval (FuncState *fs, BinOpr opr,
- expdesc *e1, expdesc *e2, int line) {
- OpCode op = binopr2op(opr, OPR_ADD, OP_ADD);
- int v2 = luaK_exp2anyreg(fs, e2); /* make sure 'e2' is in a register */
- /* 'e1' must be already in a register or it is a constant */
- lua_assert((VNIL <= e1->k && e1->k <= VKSTR) ||
- e1->k == VNONRELOC || e1->k == VRELOC);
- lua_assert(OP_ADD <= op && op <= OP_SHR);
- finishbinexpval(fs, e1, e2, op, v2, 0, line, OP_MMBIN, binopr2TM(opr));
-}
-
-
-/*
-** Code binary operators with immediate operands.
-*/
-static void codebini (FuncState *fs, OpCode op,
- expdesc *e1, expdesc *e2, int flip, int line,
- TMS event) {
- int v2 = int2sC(cast_int(e2->u.ival)); /* immediate operand */
- lua_assert(e2->k == VKINT);
- finishbinexpval(fs, e1, e2, op, v2, flip, line, OP_MMBINI, event);
-}
-
-
-/*
-** Code binary operators with K operand.
-*/
-static void codebinK (FuncState *fs, BinOpr opr,
- expdesc *e1, expdesc *e2, int flip, int line) {
- TMS event = binopr2TM(opr);
- int v2 = e2->u.info; /* K index */
- OpCode op = binopr2op(opr, OPR_ADD, OP_ADDK);
- finishbinexpval(fs, e1, e2, op, v2, flip, line, OP_MMBINK, event);
-}
-
-
-/* Try to code a binary operator negating its second operand.
-** For the metamethod, 2nd operand must keep its original value.
-*/
-static int finishbinexpneg (FuncState *fs, expdesc *e1, expdesc *e2,
- OpCode op, int line, TMS event) {
- if (!isKint(e2))
- return 0; /* not an integer constant */
- else {
- lua_Integer i2 = e2->u.ival;
- if (!(fitsC(i2) && fitsC(-i2)))
- return 0; /* not in the proper range */
- else { /* operating a small integer constant */
- int v2 = cast_int(i2);
- finishbinexpval(fs, e1, e2, op, int2sC(-v2), 0, line, OP_MMBINI, event);
- /* correct metamethod argument */
- SETARG_B(fs->f->code[fs->pc - 1], int2sC(v2));
- return 1; /* successfully coded */
- }
- }
-}
-
-
-static void swapexps (expdesc *e1, expdesc *e2) {
- expdesc temp = *e1; *e1 = *e2; *e2 = temp; /* swap 'e1' and 'e2' */
-}
-
-
-/*
-** Code binary operators with no constant operand.
-*/
-static void codebinNoK (FuncState *fs, BinOpr opr,
- expdesc *e1, expdesc *e2, int flip, int line) {
- if (flip)
- swapexps(e1, e2); /* back to original order */
- codebinexpval(fs, opr, e1, e2, line); /* use standard operators */
-}
-
-
-/*
-** Code arithmetic operators ('+', '-', ...). If second operand is a
-** constant in the proper range, use variant opcodes with K operands.
-*/
-static void codearith (FuncState *fs, BinOpr opr,
- expdesc *e1, expdesc *e2, int flip, int line) {
- if (tonumeral(e2, NULL) && luaK_exp2K(fs, e2)) /* K operand? */
- codebinK(fs, opr, e1, e2, flip, line);
- else /* 'e2' is neither an immediate nor a K operand */
- codebinNoK(fs, opr, e1, e2, flip, line);
-}
-
-
-/*
-** Code commutative operators ('+', '*'). If first operand is a
-** numeric constant, change order of operands to try to use an
-** immediate or K operator.
-*/
-static void codecommutative (FuncState *fs, BinOpr op,
- expdesc *e1, expdesc *e2, int line) {
- int flip = 0;
- if (tonumeral(e1, NULL)) { /* is first operand a numeric constant? */
- swapexps(e1, e2); /* change order */
- flip = 1;
- }
- if (op == OPR_ADD && isSCint(e2)) /* immediate operand? */
- codebini(fs, OP_ADDI, e1, e2, flip, line, TM_ADD);
- else
- codearith(fs, op, e1, e2, flip, line);
-}
-
-
-/*
-** Code bitwise operations; they are all commutative, so the function
-** tries to put an integer constant as the 2nd operand (a K operand).
-*/
-static void codebitwise (FuncState *fs, BinOpr opr,
- expdesc *e1, expdesc *e2, int line) {
- int flip = 0;
- if (e1->k == VKINT) {
- swapexps(e1, e2); /* 'e2' will be the constant operand */
- flip = 1;
- }
- if (e2->k == VKINT && luaK_exp2K(fs, e2)) /* K operand? */
- codebinK(fs, opr, e1, e2, flip, line);
- else /* no constants */
- codebinNoK(fs, opr, e1, e2, flip, line);
-}
-
-
-/*
-** Emit code for order comparisons. When using an immediate operand,
-** 'isfloat' tells whether the original value was a float.
-*/
-static void codeorder (FuncState *fs, BinOpr opr, expdesc *e1, expdesc *e2) {
- int r1, r2;
- int im;
- int isfloat = 0;
- OpCode op;
- if (isSCnumber(e2, &im, &isfloat)) {
- /* use immediate operand */
- r1 = luaK_exp2anyreg(fs, e1);
- r2 = im;
- op = binopr2op(opr, OPR_LT, OP_LTI);
- }
- else if (isSCnumber(e1, &im, &isfloat)) {
- /* transform (A < B) to (B > A) and (A <= B) to (B >= A) */
- r1 = luaK_exp2anyreg(fs, e2);
- r2 = im;
- op = binopr2op(opr, OPR_LT, OP_GTI);
- }
- else { /* regular case, compare two registers */
- r1 = luaK_exp2anyreg(fs, e1);
- r2 = luaK_exp2anyreg(fs, e2);
- op = binopr2op(opr, OPR_LT, OP_LT);
- }
- freeexps(fs, e1, e2);
- e1->u.info = condjump(fs, op, r1, r2, isfloat, 1);
- e1->k = VJMP;
-}
-
-
-/*
-** Emit code for equality comparisons ('==', '~=').
-** 'e1' was already put as RK by 'luaK_infix'.
-*/
-static void codeeq (FuncState *fs, BinOpr opr, expdesc *e1, expdesc *e2) {
- int r1, r2;
- int im;
- int isfloat = 0; /* not needed here, but kept for symmetry */
- OpCode op;
- if (e1->k != VNONRELOC) {
- lua_assert(e1->k == VK || e1->k == VKINT || e1->k == VKFLT);
- swapexps(e1, e2);
- }
- r1 = luaK_exp2anyreg(fs, e1); /* 1st expression must be in register */
- if (isSCnumber(e2, &im, &isfloat)) {
- op = OP_EQI;
- r2 = im; /* immediate operand */
- }
- else if (exp2RK(fs, e2)) { /* 2nd expression is constant? */
- op = OP_EQK;
- r2 = e2->u.info; /* constant index */
- }
- else {
- op = OP_EQ; /* will compare two registers */
- r2 = luaK_exp2anyreg(fs, e2);
- }
- freeexps(fs, e1, e2);
- e1->u.info = condjump(fs, op, r1, r2, isfloat, (opr == OPR_EQ));
- e1->k = VJMP;
-}
-
-
-/*
-** Apply prefix operation 'op' to expression 'e'.
-*/
-void luaK_prefix (FuncState *fs, UnOpr opr, expdesc *e, int line) {
- static const expdesc ef = {VKINT, {0}, NO_JUMP, NO_JUMP};
- luaK_dischargevars(fs, e);
- switch (opr) {
- case OPR_MINUS: case OPR_BNOT: /* use 'ef' as fake 2nd operand */
- if (constfolding(fs, cast_int(opr + LUA_OPUNM), e, &ef))
- break;
- /* else */ /* FALLTHROUGH */
- case OPR_LEN:
- codeunexpval(fs, unopr2op(opr), e, line);
- break;
- case OPR_NOT: codenot(fs, e); break;
- default: lua_assert(0);
- }
-}
-
-
-/*
-** Process 1st operand 'v' of binary operation 'op' before reading
-** 2nd operand.
-*/
-void luaK_infix (FuncState *fs, BinOpr op, expdesc *v) {
- luaK_dischargevars(fs, v);
- switch (op) {
- case OPR_AND: {
- luaK_goiftrue(fs, v); /* go ahead only if 'v' is true */
- break;
- }
- case OPR_OR: {
- luaK_goiffalse(fs, v); /* go ahead only if 'v' is false */
- break;
- }
- case OPR_CONCAT: {
- luaK_exp2nextreg(fs, v); /* operand must be on the stack */
- break;
- }
- case OPR_ADD: case OPR_SUB:
- case OPR_MUL: case OPR_DIV: case OPR_IDIV:
- case OPR_MOD: case OPR_POW:
- case OPR_BAND: case OPR_BOR: case OPR_BXOR:
- case OPR_SHL: case OPR_SHR: {
- if (!tonumeral(v, NULL))
- luaK_exp2anyreg(fs, v);
- /* else keep numeral, which may be folded or used as an immediate
- operand */
- break;
- }
- case OPR_EQ: case OPR_NE: {
- if (!tonumeral(v, NULL))
- exp2RK(fs, v);
- /* else keep numeral, which may be an immediate operand */
- break;
- }
- case OPR_LT: case OPR_LE:
- case OPR_GT: case OPR_GE: {
- int dummy, dummy2;
- if (!isSCnumber(v, &dummy, &dummy2))
- luaK_exp2anyreg(fs, v);
- /* else keep numeral, which may be an immediate operand */
- break;
- }
- default: lua_assert(0);
- }
-}
-
-/*
-** Create code for '(e1 .. e2)'.
-** For '(e1 .. e2.1 .. e2.2)' (which is '(e1 .. (e2.1 .. e2.2))',
-** because concatenation is right associative), merge both CONCATs.
-*/
-static void codeconcat (FuncState *fs, expdesc *e1, expdesc *e2, int line) {
- Instruction *ie2 = previousinstruction(fs);
- if (GET_OPCODE(*ie2) == OP_CONCAT) { /* is 'e2' a concatenation? */
- int n = GETARG_B(*ie2); /* # of elements concatenated in 'e2' */
- lua_assert(e1->u.info + 1 == GETARG_A(*ie2));
- freeexp(fs, e2);
- SETARG_A(*ie2, e1->u.info); /* correct first element ('e1') */
- SETARG_B(*ie2, n + 1); /* will concatenate one more element */
- }
- else { /* 'e2' is not a concatenation */
- luaK_codeABC(fs, OP_CONCAT, e1->u.info, 2, 0); /* new concat opcode */
- freeexp(fs, e2);
- luaK_fixline(fs, line);
- }
-}
-
-
-/*
-** Finalize code for binary operation, after reading 2nd operand.
-*/
-void luaK_posfix (FuncState *fs, BinOpr opr,
- expdesc *e1, expdesc *e2, int line) {
- luaK_dischargevars(fs, e2);
- if (foldbinop(opr) && constfolding(fs, cast_int(opr + LUA_OPADD), e1, e2))
- return; /* done by folding */
- switch (opr) {
- case OPR_AND: {
- lua_assert(e1->t == NO_JUMP); /* list closed by 'luaK_infix' */
- luaK_concat(fs, &e2->f, e1->f);
- *e1 = *e2;
- break;
- }
- case OPR_OR: {
- lua_assert(e1->f == NO_JUMP); /* list closed by 'luaK_infix' */
- luaK_concat(fs, &e2->t, e1->t);
- *e1 = *e2;
- break;
- }
- case OPR_CONCAT: { /* e1 .. e2 */
- luaK_exp2nextreg(fs, e2);
- codeconcat(fs, e1, e2, line);
- break;
- }
- case OPR_ADD: case OPR_MUL: {
- codecommutative(fs, opr, e1, e2, line);
- break;
- }
- case OPR_SUB: {
- if (finishbinexpneg(fs, e1, e2, OP_ADDI, line, TM_SUB))
- break; /* coded as (r1 + -I) */
- /* ELSE */
- } /* FALLTHROUGH */
- case OPR_DIV: case OPR_IDIV: case OPR_MOD: case OPR_POW: {
- codearith(fs, opr, e1, e2, 0, line);
- break;
- }
- case OPR_BAND: case OPR_BOR: case OPR_BXOR: {
- codebitwise(fs, opr, e1, e2, line);
- break;
- }
- case OPR_SHL: {
- if (isSCint(e1)) {
- swapexps(e1, e2);
- codebini(fs, OP_SHLI, e1, e2, 1, line, TM_SHL); /* I << r2 */
- }
- else if (finishbinexpneg(fs, e1, e2, OP_SHRI, line, TM_SHL)) {
- /* coded as (r1 >> -I) */;
- }
- else /* regular case (two registers) */
- codebinexpval(fs, opr, e1, e2, line);
- break;
- }
- case OPR_SHR: {
- if (isSCint(e2))
- codebini(fs, OP_SHRI, e1, e2, 0, line, TM_SHR); /* r1 >> I */
- else /* regular case (two registers) */
- codebinexpval(fs, opr, e1, e2, line);
- break;
- }
- case OPR_EQ: case OPR_NE: {
- codeeq(fs, opr, e1, e2);
- break;
- }
- case OPR_GT: case OPR_GE: {
- /* '(a > b)' <=> '(b < a)'; '(a >= b)' <=> '(b <= a)' */
- swapexps(e1, e2);
- opr = cast(BinOpr, (opr - OPR_GT) + OPR_LT);
- } /* FALLTHROUGH */
- case OPR_LT: case OPR_LE: {
- codeorder(fs, opr, e1, e2);
- break;
- }
- default: lua_assert(0);
- }
-}
-
-
-/*
-** Change line information associated with current position, by removing
-** previous info and adding it again with new line.
-*/
-void luaK_fixline (FuncState *fs, int line) {
- removelastlineinfo(fs);
- savelineinfo(fs, fs->f, line);
-}
-
-
-void luaK_settablesize (FuncState *fs, int pc, int ra, int asize, int hsize) {
- Instruction *inst = &fs->f->code[pc];
- int extra = asize / (MAXARG_vC + 1); /* higher bits of array size */
- int rc = asize % (MAXARG_vC + 1); /* lower bits of array size */
- int k = (extra > 0); /* true iff needs extra argument */
- hsize = (hsize != 0) ? luaO_ceillog2(cast_uint(hsize)) + 1 : 0;
- *inst = CREATE_vABCk(OP_NEWTABLE, ra, hsize, rc, k);
- *(inst + 1) = CREATE_Ax(OP_EXTRAARG, extra);
-}
-
-
-/*
-** Emit a SETLIST instruction.
-** 'base' is register that keeps table;
-** 'nelems' is #table plus those to be stored now;
-** 'tostore' is number of values (in registers 'base + 1',...) to add to
-** table (or LUA_MULTRET to add up to stack top).
-*/
-void luaK_setlist (FuncState *fs, int base, int nelems, int tostore) {
- lua_assert(tostore != 0);
- if (tostore == LUA_MULTRET)
- tostore = 0;
- if (nelems <= MAXARG_vC)
- luaK_codevABCk(fs, OP_SETLIST, base, tostore, nelems, 0);
- else {
- int extra = nelems / (MAXARG_vC + 1);
- nelems %= (MAXARG_vC + 1);
- luaK_codevABCk(fs, OP_SETLIST, base, tostore, nelems, 1);
- codeextraarg(fs, extra);
- }
- fs->freereg = cast_byte(base + 1); /* free registers with list values */
-}
-
-
-/*
-** return the final target of a jump (skipping jumps to jumps)
-*/
-static int finaltarget (Instruction *code, int i) {
- int count;
- for (count = 0; count < 100; count++) { /* avoid infinite loops */
- Instruction pc = code[i];
- if (GET_OPCODE(pc) != OP_JMP)
- break;
- else
- i += GETARG_sJ(pc) + 1;
- }
- return i;
-}
-
-
-/*
-** Do a final pass over the code of a function, doing small peephole
-** optimizations and adjustments.
-*/
-#include "lopnames.h"
-void luaK_finish (FuncState *fs) {
- int i;
- Proto *p = fs->f;
- if (p->flag & PF_VATAB) /* will it use a vararg table? */
- p->flag &= cast_byte(~PF_VAHID); /* then it will not use hidden args. */
- for (i = 0; i < fs->pc; i++) {
- Instruction *pc = &p->code[i];
- /* avoid "not used" warnings when assert is off (for 'onelua.c') */
- (void)luaP_isOT; (void)luaP_isIT;
- lua_assert(i == 0 || luaP_isOT(*(pc - 1)) == luaP_isIT(*pc));
- switch (GET_OPCODE(*pc)) {
- case OP_RETURN0: case OP_RETURN1: {
- if (!(fs->needclose || (p->flag & PF_VAHID)))
- break; /* no extra work */
- /* else use OP_RETURN to do the extra work */
- SET_OPCODE(*pc, OP_RETURN);
- } /* FALLTHROUGH */
- case OP_RETURN: case OP_TAILCALL: {
- if (fs->needclose)
- SETARG_k(*pc, 1); /* signal that it needs to close */
- if (p->flag & PF_VAHID) /* does it use hidden arguments? */
- SETARG_C(*pc, p->numparams + 1); /* signal that */
- break;
- }
- case OP_GETVARG: {
- if (p->flag & PF_VATAB) /* function has a vararg table? */
- SET_OPCODE(*pc, OP_GETTABLE); /* must get vararg there */
- break;
- }
- case OP_VARARG: {
- if (p->flag & PF_VATAB) /* function has a vararg table? */
- SETARG_k(*pc, 1); /* must get vararg there */
- break;
- }
- case OP_JMP: { /* to optimize jumps to jumps */
- int target = finaltarget(p->code, i);
- fixjump(fs, i, target); /* jump directly to final target */
- break;
- }
- default: break;
- }
- }
-}
diff --git a/ldebug.c b/ldebug.c
deleted file mode 100644
index 8df5f5f28b..0000000000
--- a/ldebug.c
+++ /dev/null
@@ -1,979 +0,0 @@
-/*
-** $Id: ldebug.c $
-** Debug Interface
-** See Copyright Notice in lua.h
-*/
-
-#define ldebug_c
-#define LUA_CORE
-
-#include "lprefix.h"
-
-
-#include
-#include
-#include
-
-#include "lua.h"
-
-#include "lapi.h"
-#include "lcode.h"
-#include "ldebug.h"
-#include "ldo.h"
-#include "lfunc.h"
-#include "lobject.h"
-#include "lopcodes.h"
-#include "lstate.h"
-#include "lstring.h"
-#include "ltable.h"
-#include "ltm.h"
-#include "lvm.h"
-
-
-
-#define LuaClosure(f) ((f) != NULL && (f)->c.tt == LUA_VLCL)
-
-static const char strlocal[] = "local";
-static const char strupval[] = "upvalue";
-
-static const char *funcnamefromcall (lua_State *L, CallInfo *ci,
- const char **name);
-
-
-static int currentpc (CallInfo *ci) {
- lua_assert(isLua(ci));
- return pcRel(ci->u.l.savedpc, ci_func(ci)->p);
-}
-
-
-/*
-** Get a "base line" to find the line corresponding to an instruction.
-** Base lines are regularly placed at MAXIWTHABS intervals, so usually
-** an integer division gets the right place. When the source file has
-** large sequences of empty/comment lines, it may need extra entries,
-** so the original estimate needs a correction.
-** If the original estimate is -1, the initial 'if' ensures that the
-** 'while' will run at least once.
-** The assertion that the estimate is a lower bound for the correct base
-** is valid as long as the debug info has been generated with the same
-** value for MAXIWTHABS or smaller. (Previous releases use a little
-** smaller value.)
-*/
-static int getbaseline (const Proto *f, int pc, int *basepc) {
- if (f->sizeabslineinfo == 0 || pc < f->abslineinfo[0].pc) {
- *basepc = -1; /* start from the beginning */
- return f->linedefined;
- }
- else {
- int i = pc / MAXIWTHABS - 1; /* get an estimate */
- /* estimate must be a lower bound of the correct base */
- lua_assert(i < 0 ||
- (i < f->sizeabslineinfo && f->abslineinfo[i].pc <= pc));
- while (i + 1 < f->sizeabslineinfo && pc >= f->abslineinfo[i + 1].pc)
- i++; /* low estimate; adjust it */
- *basepc = f->abslineinfo[i].pc;
- return f->abslineinfo[i].line;
- }
-}
-
-
-/*
-** Get the line corresponding to instruction 'pc' in function 'f';
-** first gets a base line and from there does the increments until
-** the desired instruction.
-*/
-int luaG_getfuncline (const Proto *f, int pc) {
- if (f->lineinfo == NULL) /* no debug information? */
- return -1;
- else {
- int basepc;
- int baseline = getbaseline(f, pc, &basepc);
- while (basepc++ < pc) { /* walk until given instruction */
- lua_assert(f->lineinfo[basepc] != ABSLINEINFO);
- baseline += f->lineinfo[basepc]; /* correct line */
- }
- return baseline;
- }
-}
-
-
-static int getcurrentline (CallInfo *ci) {
- return luaG_getfuncline(ci_func(ci)->p, currentpc(ci));
-}
-
-
-/*
-** Set 'trap' for all active Lua frames.
-** This function can be called during a signal, under "reasonable"
-** assumptions. A new 'ci' is completely linked in the list before it
-** becomes part of the "active" list, and we assume that pointers are
-** atomic; see comment in next function.
-** (A compiler doing interprocedural optimizations could, theoretically,
-** reorder memory writes in such a way that the list could be
-** temporarily broken while inserting a new element. We simply assume it
-** has no good reasons to do that.)
-*/
-static void settraps (CallInfo *ci) {
- for (; ci != NULL; ci = ci->previous)
- if (isLua(ci))
- ci->u.l.trap = 1;
-}
-
-
-/*
-** This function can be called during a signal, under "reasonable"
-** assumptions.
-** Fields 'basehookcount' and 'hookcount' (set by 'resethookcount')
-** are for debug only, and it is no problem if they get arbitrary
-** values (causes at most one wrong hook call). 'hookmask' is an atomic
-** value. We assume that pointers are atomic too (e.g., gcc ensures that
-** for all platforms where it runs). Moreover, 'hook' is always checked
-** before being called (see 'luaD_hook').
-*/
-LUA_API void lua_sethook (lua_State *L, lua_Hook func, int mask, int count) {
- if (func == NULL || mask == 0) { /* turn off hooks? */
- mask = 0;
- func = NULL;
- }
- L->hook = func;
- L->basehookcount = count;
- resethookcount(L);
- L->hookmask = cast_byte(mask);
- if (mask)
- settraps(L->ci); /* to trace inside 'luaV_execute' */
-}
-
-
-LUA_API lua_Hook lua_gethook (lua_State *L) {
- return L->hook;
-}
-
-
-LUA_API int lua_gethookmask (lua_State *L) {
- return L->hookmask;
-}
-
-
-LUA_API int lua_gethookcount (lua_State *L) {
- return L->basehookcount;
-}
-
-
-LUA_API int lua_getstack (lua_State *L, int level, lua_Debug *ar) {
- int status;
- CallInfo *ci;
- if (level < 0) return 0; /* invalid (negative) level */
- lua_lock(L);
- for (ci = L->ci; level > 0 && ci != &L->base_ci; ci = ci->previous)
- level--;
- if (level == 0 && ci != &L->base_ci) { /* level found? */
- status = 1;
- ar->i_ci = ci;
- }
- else status = 0; /* no such level */
- lua_unlock(L);
- return status;
-}
-
-
-static const char *upvalname (const Proto *p, int uv) {
- TString *s = check_exp(uv < p->sizeupvalues, p->upvalues[uv].name);
- if (s == NULL) return "?";
- else return getstr(s);
-}
-
-
-static const char *findvararg (CallInfo *ci, int n, StkId *pos) {
- if (clLvalue(s2v(ci->func.p))->p->flag & PF_VAHID) {
- int nextra = ci->u.l.nextraargs;
- if (n >= -nextra) { /* 'n' is negative */
- *pos = ci->func.p - nextra - (n + 1);
- return "(vararg)"; /* generic name for any vararg */
- }
- }
- return NULL; /* no such vararg */
-}
-
-
-const char *luaG_findlocal (lua_State *L, CallInfo *ci, int n, StkId *pos) {
- StkId base = ci->func.p + 1;
- const char *name = NULL;
- if (isLua(ci)) {
- if (n < 0) /* access to vararg values? */
- return findvararg(ci, n, pos);
- else
- name = luaF_getlocalname(ci_func(ci)->p, n, currentpc(ci));
- }
- if (name == NULL) { /* no 'standard' name? */
- StkId limit = (ci == L->ci) ? L->top.p : ci->next->func.p;
- if (limit - base >= n && n > 0) { /* is 'n' inside 'ci' stack? */
- /* generic name for any valid slot */
- name = isLua(ci) ? "(temporary)" : "(C temporary)";
- }
- else
- return NULL; /* no name */
- }
- if (pos)
- *pos = base + (n - 1);
- return name;
-}
-
-
-LUA_API const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n) {
- const char *name;
- lua_lock(L);
- if (ar == NULL) { /* information about non-active function? */
- if (!isLfunction(s2v(L->top.p - 1))) /* not a Lua function? */
- name = NULL;
- else /* consider live variables at function start (parameters) */
- name = luaF_getlocalname(clLvalue(s2v(L->top.p - 1))->p, n, 0);
- }
- else { /* active function; get information through 'ar' */
- StkId pos = NULL; /* to avoid warnings */
- name = luaG_findlocal(L, ar->i_ci, n, &pos);
- if (name) {
- setobjs2s(L, L->top.p, pos);
- api_incr_top(L);
- }
- }
- lua_unlock(L);
- return name;
-}
-
-
-LUA_API const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n) {
- StkId pos = NULL; /* to avoid warnings */
- const char *name;
- lua_lock(L);
- name = luaG_findlocal(L, ar->i_ci, n, &pos);
- if (name) {
- api_checkpop(L, 1);
- setobjs2s(L, pos, L->top.p - 1);
- L->top.p--; /* pop value */
- }
- lua_unlock(L);
- return name;
-}
-
-
-static void funcinfo (lua_Debug *ar, Closure *cl) {
- if (!LuaClosure(cl)) {
- ar->source = "=[C]";
- ar->srclen = LL("=[C]");
- ar->linedefined = -1;
- ar->lastlinedefined = -1;
- ar->what = "C";
- }
- else {
- const Proto *p = cl->l.p;
- if (p->source) {
- ar->source = getlstr(p->source, ar->srclen);
- }
- else {
- ar->source = "=?";
- ar->srclen = LL("=?");
- }
- ar->linedefined = p->linedefined;
- ar->lastlinedefined = p->lastlinedefined;
- ar->what = (ar->linedefined == 0) ? "main" : "Lua";
- }
- luaO_chunkid(ar->short_src, ar->source, ar->srclen);
-}
-
-
-static int nextline (const Proto *p, int currentline, int pc) {
- if (p->lineinfo[pc] != ABSLINEINFO)
- return currentline + p->lineinfo[pc];
- else
- return luaG_getfuncline(p, pc);
-}
-
-
-static void collectvalidlines (lua_State *L, Closure *f) {
- if (!LuaClosure(f)) {
- setnilvalue(s2v(L->top.p));
- api_incr_top(L);
- }
- else {
- const Proto *p = f->l.p;
- int currentline = p->linedefined;
- Table *t = luaH_new(L); /* new table to store active lines */
- sethvalue2s(L, L->top.p, t); /* push it on stack */
- api_incr_top(L);
- if (p->lineinfo != NULL) { /* proto with debug information? */
- int i;
- TValue v;
- setbtvalue(&v); /* boolean 'true' to be the value of all indices */
- if (!(isvararg(p))) /* regular function? */
- i = 0; /* consider all instructions */
- else { /* vararg function */
- lua_assert(GET_OPCODE(p->code[0]) == OP_VARARGPREP);
- currentline = nextline(p, currentline, 0);
- i = 1; /* skip first instruction (OP_VARARGPREP) */
- }
- for (; i < p->sizelineinfo; i++) { /* for each instruction */
- currentline = nextline(p, currentline, i); /* get its line */
- luaH_setint(L, t, currentline, &v); /* table[line] = true */
- }
- }
- }
-}
-
-
-static const char *getfuncname (lua_State *L, CallInfo *ci, const char **name) {
- /* calling function is a known function? */
- if (ci != NULL && !(ci->callstatus & CIST_TAIL))
- return funcnamefromcall(L, ci->previous, name);
- else return NULL; /* no way to find a name */
-}
-
-
-static int auxgetinfo (lua_State *L, const char *what, lua_Debug *ar,
- Closure *f, CallInfo *ci) {
- int status = 1;
- for (; *what; what++) {
- switch (*what) {
- case 'S': {
- funcinfo(ar, f);
- break;
- }
- case 'l': {
- ar->currentline = (ci && isLua(ci)) ? getcurrentline(ci) : -1;
- break;
- }
- case 'u': {
- ar->nups = (f == NULL) ? 0 : f->c.nupvalues;
- if (!LuaClosure(f)) {
- ar->isvararg = 1;
- ar->nparams = 0;
- }
- else {
- ar->isvararg = (isvararg(f->l.p)) ? 1 : 0;
- ar->nparams = f->l.p->numparams;
- }
- break;
- }
- case 't': {
- if (ci != NULL) {
- ar->istailcall = !!(ci->callstatus & CIST_TAIL);
- ar->extraargs =
- cast_uchar((ci->callstatus & MAX_CCMT) >> CIST_CCMT);
- }
- else {
- ar->istailcall = 0;
- ar->extraargs = 0;
- }
- break;
- }
- case 'n': {
- ar->namewhat = getfuncname(L, ci, &ar->name);
- if (ar->namewhat == NULL) {
- ar->namewhat = ""; /* not found */
- ar->name = NULL;
- }
- break;
- }
- case 'r': {
- if (ci == NULL || !(ci->callstatus & CIST_HOOKED))
- ar->ftransfer = ar->ntransfer = 0;
- else {
- ar->ftransfer = L->transferinfo.ftransfer;
- ar->ntransfer = L->transferinfo.ntransfer;
- }
- break;
- }
- case 'L':
- case 'f': /* handled by lua_getinfo */
- break;
- default: status = 0; /* invalid option */
- }
- }
- return status;
-}
-
-
-LUA_API int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar) {
- int status;
- Closure *cl;
- CallInfo *ci;
- TValue *func;
- lua_lock(L);
- if (*what == '>') {
- ci = NULL;
- func = s2v(L->top.p - 1);
- api_check(L, ttisfunction(func), "function expected");
- what++; /* skip the '>' */
- L->top.p--; /* pop function */
- }
- else {
- ci = ar->i_ci;
- func = s2v(ci->func.p);
- lua_assert(ttisfunction(func));
- }
- cl = ttisclosure(func) ? clvalue(func) : NULL;
- status = auxgetinfo(L, what, ar, cl, ci);
- if (strchr(what, 'f')) {
- setobj2s(L, L->top.p, func);
- api_incr_top(L);
- }
- if (strchr(what, 'L'))
- collectvalidlines(L, cl);
- lua_unlock(L);
- return status;
-}
-
-
-/*
-** {======================================================
-** Symbolic Execution
-** =======================================================
-*/
-
-
-static int filterpc (int pc, int jmptarget) {
- if (pc < jmptarget) /* is code conditional (inside a jump)? */
- return -1; /* cannot know who sets that register */
- else return pc; /* current position sets that register */
-}
-
-
-/*
-** Try to find last instruction before 'lastpc' that modified register 'reg'.
-*/
-static int findsetreg (const Proto *p, int lastpc, int reg) {
- int pc;
- int setreg = -1; /* keep last instruction that changed 'reg' */
- int jmptarget = 0; /* any code before this address is conditional */
- if (testMMMode(GET_OPCODE(p->code[lastpc])))
- lastpc--; /* previous instruction was not actually executed */
- for (pc = 0; pc < lastpc; pc++) {
- Instruction i = p->code[pc];
- OpCode op = GET_OPCODE(i);
- int a = GETARG_A(i);
- int change; /* true if current instruction changed 'reg' */
- switch (op) {
- case OP_LOADNIL: { /* set registers from 'a' to 'a+b' */
- int b = GETARG_B(i);
- change = (a <= reg && reg <= a + b);
- break;
- }
- case OP_TFORCALL: { /* affect all regs above its base */
- change = (reg >= a + 2);
- break;
- }
- case OP_CALL:
- case OP_TAILCALL: { /* affect all registers above base */
- change = (reg >= a);
- break;
- }
- case OP_JMP: { /* doesn't change registers, but changes 'jmptarget' */
- int b = GETARG_sJ(i);
- int dest = pc + 1 + b;
- /* jump does not skip 'lastpc' and is larger than current one? */
- if (dest <= lastpc && dest > jmptarget)
- jmptarget = dest; /* update 'jmptarget' */
- change = 0;
- break;
- }
- default: /* any instruction that sets A */
- change = (testAMode(op) && reg == a);
- break;
- }
- if (change)
- setreg = filterpc(pc, jmptarget);
- }
- return setreg;
-}
-
-
-/*
-** Find a "name" for the constant 'c'.
-*/
-static const char *kname (const Proto *p, int index, const char **name) {
- TValue *kvalue = &p->k[index];
- if (ttisstring(kvalue)) {
- *name = getstr(tsvalue(kvalue));
- return "constant";
- }
- else {
- *name = "?";
- return NULL;
- }
-}
-
-
-static const char *basicgetobjname (const Proto *p, int *ppc, int reg,
- const char **name) {
- int pc = *ppc;
- *name = luaF_getlocalname(p, reg + 1, pc);
- if (*name) /* is a local? */
- return strlocal;
- /* else try symbolic execution */
- *ppc = pc = findsetreg(p, pc, reg);
- if (pc != -1) { /* could find instruction? */
- Instruction i = p->code[pc];
- OpCode op = GET_OPCODE(i);
- switch (op) {
- case OP_MOVE: {
- int b = GETARG_B(i); /* move from 'b' to 'a' */
- if (b < GETARG_A(i))
- return basicgetobjname(p, ppc, b, name); /* get name for 'b' */
- break;
- }
- case OP_GETUPVAL: {
- *name = upvalname(p, GETARG_B(i));
- return strupval;
- }
- case OP_LOADK: return kname(p, GETARG_Bx(i), name);
- case OP_LOADKX: return kname(p, GETARG_Ax(p->code[pc + 1]), name);
- default: break;
- }
- }
- return NULL; /* could not find reasonable name */
-}
-
-
-/*
-** Find a "name" for the register 'c'.
-*/
-static void rname (const Proto *p, int pc, int c, const char **name) {
- const char *what = basicgetobjname(p, &pc, c, name); /* search for 'c' */
- if (!(what && *what == 'c')) /* did not find a constant name? */
- *name = "?";
-}
-
-
-/*
-** Check whether table being indexed by instruction 'i' is the
-** environment '_ENV'
-*/
-static const char *isEnv (const Proto *p, int pc, Instruction i, int isup) {
- int t = GETARG_B(i); /* table index */
- const char *name; /* name of indexed variable */
- if (isup) /* is 't' an upvalue? */
- name = upvalname(p, t);
- else { /* 't' is a register */
- const char *what = basicgetobjname(p, &pc, t, &name);
- /* 'name' must be the name of a local variable (at the current
- level or an upvalue) */
- if (what != strlocal && what != strupval)
- name = NULL; /* cannot be the variable _ENV */
- }
- return (name && strcmp(name, LUA_ENV) == 0) ? "global" : "field";
-}
-
-
-/*
-** Extend 'basicgetobjname' to handle table accesses
-*/
-static const char *getobjname (const Proto *p, int lastpc, int reg,
- const char **name) {
- const char *kind = basicgetobjname(p, &lastpc, reg, name);
- if (kind != NULL)
- return kind;
- else if (lastpc != -1) { /* could find instruction? */
- Instruction i = p->code[lastpc];
- OpCode op = GET_OPCODE(i);
- switch (op) {
- case OP_GETTABUP: {
- int k = GETARG_C(i); /* key index */
- kname(p, k, name);
- return isEnv(p, lastpc, i, 1);
- }
- case OP_GETTABLE: {
- int k = GETARG_C(i); /* key index */
- rname(p, lastpc, k, name);
- return isEnv(p, lastpc, i, 0);
- }
- case OP_GETI: {
- *name = "integer index";
- return "field";
- }
- case OP_GETFIELD: {
- int k = GETARG_C(i); /* key index */
- kname(p, k, name);
- return isEnv(p, lastpc, i, 0);
- }
- case OP_SELF: {
- int k = GETARG_C(i); /* key index */
- kname(p, k, name);
- return "method";
- }
- default: break; /* go through to return NULL */
- }
- }
- return NULL; /* could not find reasonable name */
-}
-
-
-/*
-** Try to find a name for a function based on the code that called it.
-** (Only works when function was called by a Lua function.)
-** Returns what the name is (e.g., "for iterator", "method",
-** "metamethod") and sets '*name' to point to the name.
-*/
-static const char *funcnamefromcode (lua_State *L, const Proto *p,
- int pc, const char **name) {
- TMS tm = (TMS)0; /* (initial value avoids warnings) */
- Instruction i = p->code[pc]; /* calling instruction */
- switch (GET_OPCODE(i)) {
- case OP_CALL:
- case OP_TAILCALL:
- return getobjname(p, pc, GETARG_A(i), name); /* get function name */
- case OP_TFORCALL: { /* for iterator */
- *name = "for iterator";
- return "for iterator";
- }
- /* other instructions can do calls through metamethods */
- case OP_SELF: case OP_GETTABUP: case OP_GETTABLE:
- case OP_GETI: case OP_GETFIELD:
- tm = TM_INDEX;
- break;
- case OP_SETTABUP: case OP_SETTABLE: case OP_SETI: case OP_SETFIELD:
- tm = TM_NEWINDEX;
- break;
- case OP_MMBIN: case OP_MMBINI: case OP_MMBINK: {
- tm = cast(TMS, GETARG_C(i));
- break;
- }
- case OP_UNM: tm = TM_UNM; break;
- case OP_BNOT: tm = TM_BNOT; break;
- case OP_LEN: tm = TM_LEN; break;
- case OP_CONCAT: tm = TM_CONCAT; break;
- case OP_EQ: tm = TM_EQ; break;
- /* no cases for OP_EQI and OP_EQK, as they don't call metamethods */
- case OP_LT: case OP_LTI: case OP_GTI: tm = TM_LT; break;
- case OP_LE: case OP_LEI: case OP_GEI: tm = TM_LE; break;
- case OP_CLOSE: case OP_RETURN: tm = TM_CLOSE; break;
- default:
- return NULL; /* cannot find a reasonable name */
- }
- *name = getshrstr(G(L)->tmname[tm]) + 2;
- return "metamethod";
-}
-
-
-/*
-** Try to find a name for a function based on how it was called.
-*/
-static const char *funcnamefromcall (lua_State *L, CallInfo *ci,
- const char **name) {
- if (ci->callstatus & CIST_HOOKED) { /* was it called inside a hook? */
- *name = "?";
- return "hook";
- }
- else if (ci->callstatus & CIST_FIN) { /* was it called as a finalizer? */
- *name = "__gc";
- return "metamethod"; /* report it as such */
- }
- else if (isLua(ci))
- return funcnamefromcode(L, ci_func(ci)->p, currentpc(ci), name);
- else
- return NULL;
-}
-
-/* }====================================================== */
-
-
-
-/*
-** Check whether pointer 'o' points to some value in the stack frame of
-** the current function and, if so, returns its index. Because 'o' may
-** not point to a value in this stack, we cannot compare it with the
-** region boundaries (undefined behavior in ISO C).
-*/
-static int instack (CallInfo *ci, const TValue *o) {
- int pos;
- StkId base = ci->func.p + 1;
- for (pos = 0; base + pos < ci->top.p; pos++) {
- if (o == s2v(base + pos))
- return pos;
- }
- return -1; /* not found */
-}
-
-
-/*
-** Checks whether value 'o' came from an upvalue. (That can only happen
-** with instructions OP_GETTABUP/OP_SETTABUP, which operate directly on
-** upvalues.)
-*/
-static const char *getupvalname (CallInfo *ci, const TValue *o,
- const char **name) {
- LClosure *c = ci_func(ci);
- int i;
- for (i = 0; i < c->nupvalues; i++) {
- if (c->upvals[i]->v.p == o) {
- *name = upvalname(c->p, i);
- return strupval;
- }
- }
- return NULL;
-}
-
-
-static const char *formatvarinfo (lua_State *L, const char *kind,
- const char *name) {
- if (kind == NULL)
- return ""; /* no information */
- else
- return luaO_pushfstring(L, " (%s '%s')", kind, name);
-}
-
-/*
-** Build a string with a "description" for the value 'o', such as
-** "variable 'x'" or "upvalue 'y'".
-*/
-static const char *varinfo (lua_State *L, const TValue *o) {
- CallInfo *ci = L->ci;
- const char *name = NULL; /* to avoid warnings */
- const char *kind = NULL;
- if (isLua(ci)) {
- kind = getupvalname(ci, o, &name); /* check whether 'o' is an upvalue */
- if (!kind) { /* not an upvalue? */
- int reg = instack(ci, o); /* try a register */
- if (reg >= 0) /* is 'o' a register? */
- kind = getobjname(ci_func(ci)->p, currentpc(ci), reg, &name);
- }
- }
- return formatvarinfo(L, kind, name);
-}
-
-
-/*
-** Raise a type error
-*/
-static l_noret typeerror (lua_State *L, const TValue *o, const char *op,
- const char *extra) {
- const char *t = luaT_objtypename(L, o);
- luaG_runerror(L, "attempt to %s a %s value%s", op, t, extra);
-}
-
-
-/*
-** Raise a type error with "standard" information about the faulty
-** object 'o' (using 'varinfo').
-*/
-l_noret luaG_typeerror (lua_State *L, const TValue *o, const char *op) {
- typeerror(L, o, op, varinfo(L, o));
-}
-
-
-/*
-** Raise an error for calling a non-callable object. Try to find a name
-** for the object based on how it was called ('funcnamefromcall'); if it
-** cannot get a name there, try 'varinfo'.
-*/
-l_noret luaG_callerror (lua_State *L, const TValue *o) {
- CallInfo *ci = L->ci;
- const char *name = NULL; /* to avoid warnings */
- const char *kind = funcnamefromcall(L, ci, &name);
- const char *extra = kind ? formatvarinfo(L, kind, name) : varinfo(L, o);
- typeerror(L, o, "call", extra);
-}
-
-
-l_noret luaG_forerror (lua_State *L, const TValue *o, const char *what) {
- luaG_runerror(L, "bad 'for' %s (number expected, got %s)",
- what, luaT_objtypename(L, o));
-}
-
-
-l_noret luaG_concaterror (lua_State *L, const TValue *p1, const TValue *p2) {
- if (ttisstring(p1) || cvt2str(p1)) p1 = p2;
- luaG_typeerror(L, p1, "concatenate");
-}
-
-
-l_noret luaG_opinterror (lua_State *L, const TValue *p1,
- const TValue *p2, const char *msg) {
- if (!ttisnumber(p1)) /* first operand is wrong? */
- p2 = p1; /* now second is wrong */
- luaG_typeerror(L, p2, msg);
-}
-
-
-/*
-** Error when both values are convertible to numbers, but not to integers
-*/
-l_noret luaG_tointerror (lua_State *L, const TValue *p1, const TValue *p2) {
- lua_Integer temp;
- if (!luaV_tointegerns(p1, &temp, LUA_FLOORN2I))
- p2 = p1;
- luaG_runerror(L, "number%s has no integer representation", varinfo(L, p2));
-}
-
-
-l_noret luaG_ordererror (lua_State *L, const TValue *p1, const TValue *p2) {
- const char *t1 = luaT_objtypename(L, p1);
- const char *t2 = luaT_objtypename(L, p2);
- if (strcmp(t1, t2) == 0)
- luaG_runerror(L, "attempt to compare two %s values", t1);
- else
- luaG_runerror(L, "attempt to compare %s with %s", t1, t2);
-}
-
-
-l_noret luaG_errnnil (lua_State *L, LClosure *cl, int k) {
- const char *globalname = "?"; /* default name if k == 0 */
- if (k > 0)
- kname(cl->p, k - 1, &globalname);
- luaG_runerror(L, "global '%s' already defined", globalname);
-}
-
-
-/* add src:line information to 'msg' */
-const char *luaG_addinfo (lua_State *L, const char *msg, TString *src,
- int line) {
- if (src == NULL) /* no debug information? */
- return luaO_pushfstring(L, "?:?: %s", msg);
- else {
- char buff[LUA_IDSIZE];
- size_t idlen;
- const char *id = getlstr(src, idlen);
- luaO_chunkid(buff, id, idlen);
- return luaO_pushfstring(L, "%s:%d: %s", buff, line, msg);
- }
-}
-
-
-l_noret luaG_errormsg (lua_State *L) {
- if (L->errfunc != 0) { /* is there an error handling function? */
- StkId errfunc = restorestack(L, L->errfunc);
- lua_assert(ttisfunction(s2v(errfunc)));
- setobjs2s(L, L->top.p, L->top.p - 1); /* move argument */
- setobjs2s(L, L->top.p - 1, errfunc); /* push function */
- L->top.p++; /* assume EXTRA_STACK */
- luaD_callnoyield(L, L->top.p - 2, 1); /* call it */
- }
- if (ttisnil(s2v(L->top.p - 1))) { /* error object is nil? */
- /* change it to a proper message */
- setsvalue2s(L, L->top.p - 1, luaS_newliteral(L, ""));
- }
- luaD_throw(L, LUA_ERRRUN);
-}
-
-
-l_noret luaG_runerror (lua_State *L, const char *fmt, ...) {
- CallInfo *ci = L->ci;
- const char *msg;
- va_list argp;
- luaC_checkGC(L); /* error message uses memory */
- pushvfstring(L, argp, fmt, msg);
- if (isLua(ci)) { /* Lua function? */
- /* add source:line information */
- luaG_addinfo(L, msg, ci_func(ci)->p->source, getcurrentline(ci));
- setobjs2s(L, L->top.p - 2, L->top.p - 1); /* remove 'msg' */
- L->top.p--;
- }
- luaG_errormsg(L);
-}
-
-
-/*
-** Check whether new instruction 'newpc' is in a different line from
-** previous instruction 'oldpc'. More often than not, 'newpc' is only
-** one or a few instructions after 'oldpc' (it must be after, see
-** caller), so try to avoid calling 'luaG_getfuncline'. If they are
-** too far apart, there is a good chance of a ABSLINEINFO in the way,
-** so it goes directly to 'luaG_getfuncline'.
-*/
-static int changedline (const Proto *p, int oldpc, int newpc) {
- if (p->lineinfo == NULL) /* no debug information? */
- return 0;
- if (newpc - oldpc < MAXIWTHABS / 2) { /* not too far apart? */
- int delta = 0; /* line difference */
- int pc = oldpc;
- for (;;) {
- int lineinfo = p->lineinfo[++pc];
- if (lineinfo == ABSLINEINFO)
- break; /* cannot compute delta; fall through */
- delta += lineinfo;
- if (pc == newpc)
- return (delta != 0); /* delta computed successfully */
- }
- }
- /* either instructions are too far apart or there is an absolute line
- info in the way; compute line difference explicitly */
- return (luaG_getfuncline(p, oldpc) != luaG_getfuncline(p, newpc));
-}
-
-
-/*
-** Traces Lua calls. If code is running the first instruction of a function,
-** and function is not vararg, and it is not coming from an yield,
-** calls 'luaD_hookcall'. (Vararg functions will call 'luaD_hookcall'
-** after adjusting its variable arguments; otherwise, they could call
-** a line/count hook before the call hook. Functions coming from
-** an yield already called 'luaD_hookcall' before yielding.)
-*/
-int luaG_tracecall (lua_State *L) {
- CallInfo *ci = L->ci;
- Proto *p = ci_func(ci)->p;
- ci->u.l.trap = 1; /* ensure hooks will be checked */
- if (ci->u.l.savedpc == p->code) { /* first instruction (not resuming)? */
- if (isvararg(p))
- return 0; /* hooks will start at VARARGPREP instruction */
- else if (!(ci->callstatus & CIST_HOOKYIELD)) /* not yielded? */
- luaD_hookcall(L, ci); /* check 'call' hook */
- }
- return 1; /* keep 'trap' on */
-}
-
-
-/*
-** Traces the execution of a Lua function. Called before the execution
-** of each opcode, when debug is on. 'L->oldpc' stores the last
-** instruction traced, to detect line changes. When entering a new
-** function, 'npci' will be zero and will test as a new line whatever
-** the value of 'oldpc'. Some exceptional conditions may return to
-** a function without setting 'oldpc'. In that case, 'oldpc' may be
-** invalid; if so, use zero as a valid value. (A wrong but valid 'oldpc'
-** at most causes an extra call to a line hook.)
-** This function is not "Protected" when called, so it should correct
-** 'L->top.p' before calling anything that can run the GC.
-*/
-int luaG_traceexec (lua_State *L, const Instruction *pc) {
- CallInfo *ci = L->ci;
- lu_byte mask = cast_byte(L->hookmask);
- const Proto *p = ci_func(ci)->p;
- int counthook;
- if (!(mask & (LUA_MASKLINE | LUA_MASKCOUNT))) { /* no hooks? */
- ci->u.l.trap = 0; /* don't need to stop again */
- return 0; /* turn off 'trap' */
- }
- pc++; /* reference is always next instruction */
- ci->u.l.savedpc = pc; /* save 'pc' */
- counthook = (mask & LUA_MASKCOUNT) && (--L->hookcount == 0);
- if (counthook)
- resethookcount(L); /* reset count */
- else if (!(mask & LUA_MASKLINE))
- return 1; /* no line hook and count != 0; nothing to be done now */
- if (ci->callstatus & CIST_HOOKYIELD) { /* hook yielded last time? */
- ci->callstatus &= ~CIST_HOOKYIELD; /* erase mark */
- return 1; /* do not call hook again (VM yielded, so it did not move) */
- }
- if (!luaP_isIT(*(ci->u.l.savedpc - 1))) /* top not being used? */
- L->top.p = ci->top.p; /* correct top */
- if (counthook)
- luaD_hook(L, LUA_HOOKCOUNT, -1, 0, 0); /* call count hook */
- if (mask & LUA_MASKLINE) {
- /* 'L->oldpc' may be invalid; use zero in this case */
- int oldpc = (L->oldpc < p->sizecode) ? L->oldpc : 0;
- int npci = pcRel(pc, p);
- if (npci <= oldpc || /* call hook when jump back (loop), */
- changedline(p, oldpc, npci)) { /* or when enter new line */
- int newline = luaG_getfuncline(p, npci);
- luaD_hook(L, LUA_HOOKLINE, newline, 0, 0); /* call line hook */
- }
- L->oldpc = npci; /* 'pc' of last call to line hook */
- }
- if (L->status == LUA_YIELD) { /* did hook yield? */
- if (counthook)
- L->hookcount = 1; /* undo decrement to zero */
- ci->callstatus |= CIST_HOOKYIELD; /* mark that it yielded */
- luaD_throw(L, LUA_YIELD);
- }
- return 1; /* keep 'trap' on */
-}
-
diff --git a/ldebug.h b/ldebug.h
deleted file mode 100644
index 20d07818b4..0000000000
--- a/ldebug.h
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
-** $Id: ldebug.h $
-** Auxiliary functions from Debug Interface module
-** See Copyright Notice in lua.h
-*/
-
-#ifndef ldebug_h
-#define ldebug_h
-
-
-#include "lstate.h"
-
-
-#define pcRel(pc, p) (cast_int((pc) - (p)->code) - 1)
-
-
-/* Active Lua function (given call info) */
-#define ci_func(ci) (clLvalue(s2v((ci)->func.p)))
-
-
-#define resethookcount(L) (L->hookcount = L->basehookcount)
-
-/*
-** mark for entries in 'lineinfo' array that has absolute information in
-** 'abslineinfo' array
-*/
-#define ABSLINEINFO (-0x80)
-
-
-/*
-** MAXimum number of successive Instructions WiTHout ABSolute line
-** information. (A power of two allows fast divisions.)
-*/
-#if !defined(MAXIWTHABS)
-#define MAXIWTHABS 128
-#endif
-
-
-LUAI_FUNC int luaG_getfuncline (const Proto *f, int pc);
-LUAI_FUNC const char *luaG_findlocal (lua_State *L, CallInfo *ci, int n,
- StkId *pos);
-LUAI_FUNC l_noret luaG_typeerror (lua_State *L, const TValue *o,
- const char *opname);
-LUAI_FUNC l_noret luaG_callerror (lua_State *L, const TValue *o);
-LUAI_FUNC l_noret luaG_forerror (lua_State *L, const TValue *o,
- const char *what);
-LUAI_FUNC l_noret luaG_concaterror (lua_State *L, const TValue *p1,
- const TValue *p2);
-LUAI_FUNC l_noret luaG_opinterror (lua_State *L, const TValue *p1,
- const TValue *p2,
- const char *msg);
-LUAI_FUNC l_noret luaG_tointerror (lua_State *L, const TValue *p1,
- const TValue *p2);
-LUAI_FUNC l_noret luaG_ordererror (lua_State *L, const TValue *p1,
- const TValue *p2);
-LUAI_FUNC l_noret luaG_errnnil (lua_State *L, LClosure *cl, int k);
-LUAI_FUNC l_noret luaG_runerror (lua_State *L, const char *fmt, ...);
-LUAI_FUNC const char *luaG_addinfo (lua_State *L, const char *msg,
- TString *src, int line);
-LUAI_FUNC l_noret luaG_errormsg (lua_State *L);
-LUAI_FUNC int luaG_traceexec (lua_State *L, const Instruction *pc);
-LUAI_FUNC int luaG_tracecall (lua_State *L);
-
-
-#endif
diff --git a/ldo.c b/ldo.c
deleted file mode 100644
index 12e0364b98..0000000000
--- a/ldo.c
+++ /dev/null
@@ -1,1172 +0,0 @@
-/*
-** $Id: ldo.c $
-** Stack and Call structure of Lua
-** See Copyright Notice in lua.h
-*/
-
-#define ldo_c
-#define LUA_CORE
-
-#include "lprefix.h"
-
-
-#include
-#include
-#include
-
-#include "lua.h"
-
-#include "lapi.h"
-#include "ldebug.h"
-#include "ldo.h"
-#include "lfunc.h"
-#include "lgc.h"
-#include "lmem.h"
-#include "lobject.h"
-#include "lopcodes.h"
-#include "lparser.h"
-#include "lstate.h"
-#include "lstring.h"
-#include "ltable.h"
-#include "ltm.h"
-#include "lundump.h"
-#include "lvm.h"
-#include "lzio.h"
-
-
-
-#define errorstatus(s) ((s) > LUA_YIELD)
-
-
-/*
-** these macros allow user-specific actions when a thread is
-** resumed/yielded.
-*/
-#if !defined(luai_userstateresume)
-#define luai_userstateresume(L,n) ((void)L)
-#endif
-
-#if !defined(luai_userstateyield)
-#define luai_userstateyield(L,n) ((void)L)
-#endif
-
-
-/*
-** {======================================================
-** Error-recovery functions
-** =======================================================
-*/
-
-/* chained list of long jump buffers */
-typedef struct lua_longjmp {
- struct lua_longjmp *previous;
- jmp_buf b;
- volatile TStatus status; /* error code */
-} lua_longjmp;
-
-
-/*
-** LUAI_THROW/LUAI_TRY define how Lua does exception handling. By
-** default, Lua handles errors with exceptions when compiling as
-** C++ code, with _longjmp/_setjmp when available (POSIX), and with
-** longjmp/setjmp otherwise.
-*/
-#if !defined(LUAI_THROW) /* { */
-
-#if defined(__cplusplus) && !defined(LUA_USE_LONGJMP) /* { */
-
-/* C++ exceptions */
-#define LUAI_THROW(L,c) throw(c)
-
-static void LUAI_TRY (lua_State *L, lua_longjmp *c, Pfunc f, void *ud) {
- try {
- f(L, ud); /* call function protected */
- }
- catch (lua_longjmp *c1) { /* Lua error */
- if (c1 != c) /* not the correct level? */
- throw; /* rethrow to upper level */
- }
- catch (...) { /* non-Lua exception */
- c->status = -1; /* create some error code */
- }
-}
-
-
-#elif defined(LUA_USE_POSIX) /* }{ */
-
-/* in POSIX, use _longjmp/_setjmp (more efficient) */
-#define LUAI_THROW(L,c) _longjmp((c)->b, 1)
-#define LUAI_TRY(L,c,f,ud) if (_setjmp((c)->b) == 0) ((f)(L, ud))
-
-#else /* }{ */
-
-/* ISO C handling with long jumps */
-#define LUAI_THROW(L,c) longjmp((c)->b, 1)
-#define LUAI_TRY(L,c,f,ud) if (setjmp((c)->b) == 0) ((f)(L, ud))
-
-#endif /* } */
-
-#endif /* } */
-
-
-void luaD_seterrorobj (lua_State *L, TStatus errcode, StkId oldtop) {
- if (errcode == LUA_ERRMEM) { /* memory error? */
- setsvalue2s(L, oldtop, G(L)->memerrmsg); /* reuse preregistered msg. */
- }
- else {
- lua_assert(errorstatus(errcode)); /* must be a real error */
- lua_assert(!ttisnil(s2v(L->top.p - 1))); /* with a non-nil object */
- setobjs2s(L, oldtop, L->top.p - 1); /* move it to 'oldtop' */
- }
- L->top.p = oldtop + 1; /* top goes back to old top plus error object */
-}
-
-
-l_noret luaD_throw (lua_State *L, TStatus errcode) {
- if (L->errorJmp) { /* thread has an error handler? */
- L->errorJmp->status = errcode; /* set status */
- LUAI_THROW(L, L->errorJmp); /* jump to it */
- }
- else { /* thread has no error handler */
- global_State *g = G(L);
- lua_State *mainth = mainthread(g);
- errcode = luaE_resetthread(L, errcode); /* close all upvalues */
- L->status = errcode;
- if (mainth->errorJmp) { /* main thread has a handler? */
- setobjs2s(L, mainth->top.p++, L->top.p - 1); /* copy error obj. */
- luaD_throw(mainth, errcode); /* re-throw in main thread */
- }
- else { /* no handler at all; abort */
- if (g->panic) { /* panic function? */
- lua_unlock(L);
- g->panic(L); /* call panic function (last chance to jump out) */
- }
- abort();
- }
- }
-}
-
-
-l_noret luaD_throwbaselevel (lua_State *L, TStatus errcode) {
- if (L->errorJmp) {
- /* unroll error entries up to the first level */
- while (L->errorJmp->previous != NULL)
- L->errorJmp = L->errorJmp->previous;
- }
- luaD_throw(L, errcode);
-}
-
-
-TStatus luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud) {
- l_uint32 oldnCcalls = L->nCcalls;
- lua_longjmp lj;
- lj.status = LUA_OK;
- lj.previous = L->errorJmp; /* chain new error handler */
- L->errorJmp = &lj;
- LUAI_TRY(L, &lj, f, ud); /* call 'f' catching errors */
- L->errorJmp = lj.previous; /* restore old error handler */
- L->nCcalls = oldnCcalls;
- return lj.status;
-}
-
-/* }====================================================== */
-
-
-/*
-** {==================================================================
-** Stack reallocation
-** ===================================================================
-*/
-
-/* some stack space for error handling */
-#define STACKERRSPACE 200
-
-
-/*
-** LUAI_MAXSTACK limits the size of the Lua stack.
-** It must fit into INT_MAX/2.
-*/
-
-#if !defined(LUAI_MAXSTACK)
-#if 1000000 < (INT_MAX / 2)
-#define LUAI_MAXSTACK 1000000
-#else
-#define LUAI_MAXSTACK (INT_MAX / 2u)
-#endif
-#endif
-
-
-/* maximum stack size that respects size_t */
-#define MAXSTACK_BYSIZET ((MAX_SIZET / sizeof(StackValue)) - STACKERRSPACE)
-
-/*
-** Minimum between LUAI_MAXSTACK and MAXSTACK_BYSIZET
-** (Maximum size for the stack must respect size_t.)
-*/
-#define MAXSTACK cast_int(LUAI_MAXSTACK < MAXSTACK_BYSIZET \
- ? LUAI_MAXSTACK : MAXSTACK_BYSIZET)
-
-
-/* stack size with extra space for error handling */
-#define ERRORSTACKSIZE (MAXSTACK + STACKERRSPACE)
-
-
-/* raise a stack error while running the message handler */
-l_noret luaD_errerr (lua_State *L) {
- TString *msg = luaS_newliteral(L, "error in error handling");
- setsvalue2s(L, L->top.p, msg);
- L->top.p++; /* assume EXTRA_STACK */
- luaD_throw(L, LUA_ERRERR);
-}
-
-
-/*
-** Check whether stacks have enough space to run a simple function (such
-** as a finalizer): At least BASIC_STACK_SIZE in the Lua stack, two
-** available CallInfos, and two "slots" in the C stack.
-*/
-int luaD_checkminstack (lua_State *L) {
- if (getCcalls(L) >= LUAI_MAXCCALLS - 2)
- return 0; /* not enough C-stack slots */
- if (L->ci->next == NULL && luaE_extendCI(L, 0) == NULL)
- return 0; /* unable to allocate first ci */
- if (L->ci->next->next == NULL && luaE_extendCI(L, 0) == NULL)
- return 0; /* unable to allocate second ci */
- if (L->stack_last.p - L->top.p >= BASIC_STACK_SIZE)
- return 1; /* enough (BASIC_STACK_SIZE) free slots in the Lua stack */
- else /* try to grow stack to a size with enough free slots */
- return luaD_growstack(L, BASIC_STACK_SIZE, 0);
-}
-
-
-/*
-** In ISO C, any pointer use after the pointer has been deallocated is
-** undefined behavior. So, before a stack reallocation, all pointers
-** should be changed to offsets, and after the reallocation they should
-** be changed back to pointers. As during the reallocation the pointers
-** are invalid, the reallocation cannot run emergency collections.
-** Alternatively, we can use the old address after the deallocation.
-** That is not strict ISO C, but seems to work fine everywhere.
-** The following macro chooses how strict is the code.
-*/
-#if !defined(LUAI_STRICT_ADDRESS)
-#define LUAI_STRICT_ADDRESS 1
-#endif
-
-#if LUAI_STRICT_ADDRESS
-/*
-** Change all pointers to the stack into offsets.
-*/
-static void relstack (lua_State *L) {
- CallInfo *ci;
- UpVal *up;
- L->top.offset = savestack(L, L->top.p);
- L->tbclist.offset = savestack(L, L->tbclist.p);
- for (up = L->openupval; up != NULL; up = up->u.open.next)
- up->v.offset = savestack(L, uplevel(up));
- for (ci = L->ci; ci != NULL; ci = ci->previous) {
- ci->top.offset = savestack(L, ci->top.p);
- ci->func.offset = savestack(L, ci->func.p);
- }
-}
-
-
-/*
-** Change back all offsets into pointers.
-*/
-static void correctstack (lua_State *L, StkId oldstack) {
- CallInfo *ci;
- UpVal *up;
- UNUSED(oldstack);
- L->top.p = restorestack(L, L->top.offset);
- L->tbclist.p = restorestack(L, L->tbclist.offset);
- for (up = L->openupval; up != NULL; up = up->u.open.next)
- up->v.p = s2v(restorestack(L, up->v.offset));
- for (ci = L->ci; ci != NULL; ci = ci->previous) {
- ci->top.p = restorestack(L, ci->top.offset);
- ci->func.p = restorestack(L, ci->func.offset);
- if (isLua(ci))
- ci->u.l.trap = 1; /* signal to update 'trap' in 'luaV_execute' */
- }
-}
-
-#else
-/*
-** Assume that it is fine to use an address after its deallocation,
-** as long as we do not dereference it.
-*/
-
-static void relstack (lua_State *L) { UNUSED(L); } /* do nothing */
-
-
-/*
-** Correct pointers into 'oldstack' to point into 'L->stack'.
-*/
-static void correctstack (lua_State *L, StkId oldstack) {
- CallInfo *ci;
- UpVal *up;
- StkId newstack = L->stack.p;
- if (oldstack == newstack)
- return;
- L->top.p = L->top.p - oldstack + newstack;
- L->tbclist.p = L->tbclist.p - oldstack + newstack;
- for (up = L->openupval; up != NULL; up = up->u.open.next)
- up->v.p = s2v(uplevel(up) - oldstack + newstack);
- for (ci = L->ci; ci != NULL; ci = ci->previous) {
- ci->top.p = ci->top.p - oldstack + newstack;
- ci->func.p = ci->func.p - oldstack + newstack;
- if (isLua(ci))
- ci->u.l.trap = 1; /* signal to update 'trap' in 'luaV_execute' */
- }
-}
-#endif
-
-
-/*
-** Reallocate the stack to a new size, correcting all pointers into it.
-** In case of allocation error, raise an error or return false according
-** to 'raiseerror'.
-*/
-int luaD_reallocstack (lua_State *L, int newsize, int raiseerror) {
- int oldsize = stacksize(L);
- int i;
- StkId newstack;
- StkId oldstack = L->stack.p;
- lu_byte oldgcstop = G(L)->gcstopem;
- lua_assert(newsize <= MAXSTACK || newsize == ERRORSTACKSIZE);
- relstack(L); /* change pointers to offsets */
- G(L)->gcstopem = 1; /* stop emergency collection */
- newstack = luaM_reallocvector(L, oldstack, oldsize + EXTRA_STACK,
- newsize + EXTRA_STACK, StackValue);
- G(L)->gcstopem = oldgcstop; /* restore emergency collection */
- if (l_unlikely(newstack == NULL)) { /* reallocation failed? */
- correctstack(L, oldstack); /* change offsets back to pointers */
- if (raiseerror)
- luaM_error(L);
- else return 0; /* do not raise an error */
- }
- L->stack.p = newstack;
- correctstack(L, oldstack); /* change offsets back to pointers */
- L->stack_last.p = L->stack.p + newsize;
- for (i = oldsize + EXTRA_STACK; i < newsize + EXTRA_STACK; i++)
- setnilvalue(s2v(newstack + i)); /* erase new segment */
- return 1;
-}
-
-
-/*
-** Try to grow the stack by at least 'n' elements. When 'raiseerror'
-** is true, raises any error; otherwise, return 0 in case of errors.
-*/
-int luaD_growstack (lua_State *L, int n, int raiseerror) {
- int size = stacksize(L);
- if (l_unlikely(size > MAXSTACK)) {
- /* if stack is larger than maximum, thread is already using the
- extra space reserved for errors, that is, thread is handling
- a stack error; cannot grow further than that. */
- lua_assert(stacksize(L) == ERRORSTACKSIZE);
- if (raiseerror)
- luaD_errerr(L); /* stack error inside message handler */
- return 0; /* if not 'raiseerror', just signal it */
- }
- else if (n < MAXSTACK) { /* avoids arithmetic overflows */
- int newsize = size + (size >> 1); /* tentative new size (size * 1.5) */
- int needed = cast_int(L->top.p - L->stack.p) + n;
- if (newsize > MAXSTACK) /* cannot cross the limit */
- newsize = MAXSTACK;
- if (newsize < needed) /* but must respect what was asked for */
- newsize = needed;
- if (l_likely(newsize <= MAXSTACK))
- return luaD_reallocstack(L, newsize, raiseerror);
- }
- /* else stack overflow */
- /* add extra size to be able to handle the error message */
- luaD_reallocstack(L, ERRORSTACKSIZE, raiseerror);
- if (raiseerror)
- luaG_runerror(L, "stack overflow");
- return 0;
-}
-
-
-/*
-** Compute how much of the stack is being used, by computing the
-** maximum top of all call frames in the stack and the current top.
-*/
-static int stackinuse (lua_State *L) {
- CallInfo *ci;
- int res;
- StkId lim = L->top.p;
- for (ci = L->ci; ci != NULL; ci = ci->previous) {
- if (lim < ci->top.p) lim = ci->top.p;
- }
- lua_assert(lim <= L->stack_last.p + EXTRA_STACK);
- res = cast_int(lim - L->stack.p) + 1; /* part of stack in use */
- if (res < LUA_MINSTACK)
- res = LUA_MINSTACK; /* ensure a minimum size */
- return res;
-}
-
-
-/*
-** If stack size is more than 3 times the current use, reduce that size
-** to twice the current use. (So, the final stack size is at most 2/3 the
-** previous size, and half of its entries are empty.)
-** As a particular case, if stack was handling a stack overflow and now
-** it is not, 'max' (limited by MAXSTACK) will be smaller than
-** stacksize (equal to ERRORSTACKSIZE in this case), and so the stack
-** will be reduced to a "regular" size.
-*/
-void luaD_shrinkstack (lua_State *L) {
- int inuse = stackinuse(L);
- int max = (inuse > MAXSTACK / 3) ? MAXSTACK : inuse * 3;
- /* if thread is currently not handling a stack overflow and its
- size is larger than maximum "reasonable" size, shrink it */
- if (inuse <= MAXSTACK && stacksize(L) > max) {
- int nsize = (inuse > MAXSTACK / 2) ? MAXSTACK : inuse * 2;
- luaD_reallocstack(L, nsize, 0); /* ok if that fails */
- }
- else /* don't change stack */
- condmovestack(L,(void)0,(void)0); /* (change only for debugging) */
- luaE_shrinkCI(L); /* shrink CI list */
-}
-
-
-void luaD_inctop (lua_State *L) {
- L->top.p++;
- luaD_checkstack(L, 1);
-}
-
-/* }================================================================== */
-
-
-/*
-** Call a hook for the given event. Make sure there is a hook to be
-** called. (Both 'L->hook' and 'L->hookmask', which trigger this
-** function, can be changed asynchronously by signals.)
-*/
-void luaD_hook (lua_State *L, int event, int line,
- int ftransfer, int ntransfer) {
- lua_Hook hook = L->hook;
- if (hook && L->allowhook) { /* make sure there is a hook */
- CallInfo *ci = L->ci;
- ptrdiff_t top = savestack(L, L->top.p); /* preserve original 'top' */
- ptrdiff_t ci_top = savestack(L, ci->top.p); /* idem for 'ci->top' */
- lua_Debug ar;
- ar.event = event;
- ar.currentline = line;
- ar.i_ci = ci;
- L->transferinfo.ftransfer = ftransfer;
- L->transferinfo.ntransfer = ntransfer;
- if (isLua(ci) && L->top.p < ci->top.p)
- L->top.p = ci->top.p; /* protect entire activation register */
- luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */
- if (ci->top.p < L->top.p + LUA_MINSTACK)
- ci->top.p = L->top.p + LUA_MINSTACK;
- L->allowhook = 0; /* cannot call hooks inside a hook */
- ci->callstatus |= CIST_HOOKED;
- lua_unlock(L);
- (*hook)(L, &ar);
- lua_lock(L);
- lua_assert(!L->allowhook);
- L->allowhook = 1;
- ci->top.p = restorestack(L, ci_top);
- L->top.p = restorestack(L, top);
- ci->callstatus &= ~CIST_HOOKED;
- }
-}
-
-
-/*
-** Executes a call hook for Lua functions. This function is called
-** whenever 'hookmask' is not zero, so it checks whether call hooks are
-** active.
-*/
-void luaD_hookcall (lua_State *L, CallInfo *ci) {
- L->oldpc = 0; /* set 'oldpc' for new function */
- if (L->hookmask & LUA_MASKCALL) { /* is call hook on? */
- int event = (ci->callstatus & CIST_TAIL) ? LUA_HOOKTAILCALL
- : LUA_HOOKCALL;
- Proto *p = ci_func(ci)->p;
- ci->u.l.savedpc++; /* hooks assume 'pc' is already incremented */
- luaD_hook(L, event, -1, 1, p->numparams);
- ci->u.l.savedpc--; /* correct 'pc' */
- }
-}
-
-
-/*
-** Executes a return hook for Lua and C functions and sets/corrects
-** 'oldpc'. (Note that this correction is needed by the line hook, so it
-** is done even when return hooks are off.)
-*/
-static void rethook (lua_State *L, CallInfo *ci, int nres) {
- if (L->hookmask & LUA_MASKRET) { /* is return hook on? */
- StkId firstres = L->top.p - nres; /* index of first result */
- int delta = 0; /* correction for vararg functions */
- int ftransfer;
- if (isLua(ci)) {
- Proto *p = ci_func(ci)->p;
- if (p->flag & PF_VAHID)
- delta = ci->u.l.nextraargs + p->numparams + 1;
- }
- ci->func.p += delta; /* if vararg, back to virtual 'func' */
- ftransfer = cast_int(firstres - ci->func.p);
- luaD_hook(L, LUA_HOOKRET, -1, ftransfer, nres); /* call it */
- ci->func.p -= delta;
- }
- if (isLua(ci = ci->previous))
- L->oldpc = pcRel(ci->u.l.savedpc, ci_func(ci)->p); /* set 'oldpc' */
-}
-
-
-/*
-** Check whether 'func' has a '__call' metafield. If so, put it in the
-** stack, below original 'func', so that 'luaD_precall' can call it.
-** Raise an error if there is no '__call' metafield.
-** Bits CIST_CCMT in status count how many _call metamethods were
-** invoked and how many corresponding extra arguments were pushed.
-** (This count will be saved in the 'callstatus' of the call).
-** Raise an error if this counter overflows.
-*/
-static unsigned tryfuncTM (lua_State *L, StkId func, unsigned status) {
- const TValue *tm;
- StkId p;
- tm = luaT_gettmbyobj(L, s2v(func), TM_CALL);
- if (l_unlikely(ttisnil(tm))) /* no metamethod? */
- luaG_callerror(L, s2v(func));
- for (p = L->top.p; p > func; p--) /* open space for metamethod */
- setobjs2s(L, p, p-1);
- L->top.p++; /* stack space pre-allocated by the caller */
- setobj2s(L, func, tm); /* metamethod is the new function to be called */
- if ((status & MAX_CCMT) == MAX_CCMT) /* is counter full? */
- luaG_runerror(L, "'__call' chain too long");
- return status + (1u << CIST_CCMT); /* increment counter */
-}
-
-
-/* Generic case for 'moveresult' */
-l_sinline void genmoveresults (lua_State *L, StkId res, int nres,
- int wanted) {
- StkId firstresult = L->top.p - nres; /* index of first result */
- int i;
- if (nres > wanted) /* extra results? */
- nres = wanted; /* don't need them */
- for (i = 0; i < nres; i++) /* move all results to correct place */
- setobjs2s(L, res + i, firstresult + i);
- for (; i < wanted; i++) /* complete wanted number of results */
- setnilvalue(s2v(res + i));
- L->top.p = res + wanted; /* top points after the last result */
-}
-
-
-/*
-** Given 'nres' results at 'firstResult', move 'fwanted-1' of them
-** to 'res'. Handle most typical cases (zero results for commands,
-** one result for expressions, multiple results for tail calls/single
-** parameters) separated. The flag CIST_TBC in 'fwanted', if set,
-** forces the switch to go to the default case.
-*/
-l_sinline void moveresults (lua_State *L, StkId res, int nres,
- l_uint32 fwanted) {
- switch (fwanted) { /* handle typical cases separately */
- case 0 + 1: /* no values needed */
- L->top.p = res;
- return;
- case 1 + 1: /* one value needed */
- if (nres == 0) /* no results? */
- setnilvalue(s2v(res)); /* adjust with nil */
- else /* at least one result */
- setobjs2s(L, res, L->top.p - nres); /* move it to proper place */
- L->top.p = res + 1;
- return;
- case LUA_MULTRET + 1:
- genmoveresults(L, res, nres, nres); /* we want all results */
- break;
- default: { /* two/more results and/or to-be-closed variables */
- int wanted = get_nresults(fwanted);
- if (fwanted & CIST_TBC) { /* to-be-closed variables? */
- L->ci->u2.nres = nres;
- L->ci->callstatus |= CIST_CLSRET; /* in case of yields */
- res = luaF_close(L, res, CLOSEKTOP, 1);
- L->ci->callstatus &= ~CIST_CLSRET;
- if (L->hookmask) { /* if needed, call hook after '__close's */
- ptrdiff_t savedres = savestack(L, res);
- rethook(L, L->ci, nres);
- res = restorestack(L, savedres); /* hook can move stack */
- }
- if (wanted == LUA_MULTRET)
- wanted = nres; /* we want all results */
- }
- genmoveresults(L, res, nres, wanted);
- break;
- }
- }
-}
-
-
-/*
-** Finishes a function call: calls hook if necessary, moves current
-** number of results to proper place, and returns to previous call
-** info. If function has to close variables, hook must be called after
-** that.
-*/
-void luaD_poscall (lua_State *L, CallInfo *ci, int nres) {
- l_uint32 fwanted = ci->callstatus & (CIST_TBC | CIST_NRESULTS);
- if (l_unlikely(L->hookmask) && !(fwanted & CIST_TBC))
- rethook(L, ci, nres);
- /* move results to proper place */
- moveresults(L, ci->func.p, nres, fwanted);
- /* function cannot be in any of these cases when returning */
- lua_assert(!(ci->callstatus &
- (CIST_HOOKED | CIST_YPCALL | CIST_FIN | CIST_CLSRET)));
- L->ci = ci->previous; /* back to caller (after closing variables) */
-}
-
-
-
-#define next_ci(L) (L->ci->next ? L->ci->next : luaE_extendCI(L, 1))
-
-
-/*
-** Allocate and initialize CallInfo structure. At this point, the
-** only valid fields in the call status are number of results,
-** CIST_C (if it's a C function), and number of extra arguments.
-** (All these bit-fields fit in 16-bit values.)
-*/
-l_sinline CallInfo *prepCallInfo (lua_State *L, StkId func, unsigned status,
- StkId top) {
- CallInfo *ci = L->ci = next_ci(L); /* new frame */
- ci->func.p = func;
- lua_assert((status & ~(CIST_NRESULTS | CIST_C | MAX_CCMT)) == 0);
- ci->callstatus = status;
- ci->top.p = top;
- return ci;
-}
-
-
-/*
-** precall for C functions
-*/
-l_sinline int precallC (lua_State *L, StkId func, unsigned status,
- lua_CFunction f) {
- int n; /* number of returns */
- CallInfo *ci;
- checkstackp(L, LUA_MINSTACK, func); /* ensure minimum stack size */
- L->ci = ci = prepCallInfo(L, func, status | CIST_C,
- L->top.p + LUA_MINSTACK);
- lua_assert(ci->top.p <= L->stack_last.p);
- if (l_unlikely(L->hookmask & LUA_MASKCALL)) {
- int narg = cast_int(L->top.p - func) - 1;
- luaD_hook(L, LUA_HOOKCALL, -1, 1, narg);
- }
- lua_unlock(L);
- n = (*f)(L); /* do the actual call */
- lua_lock(L);
- api_checknelems(L, n);
- luaD_poscall(L, ci, n);
- return n;
-}
-
-
-/*
-** Prepare a function for a tail call, building its call info on top
-** of the current call info. 'narg1' is the number of arguments plus 1
-** (so that it includes the function itself). Return the number of
-** results, if it was a C function, or -1 for a Lua function.
-*/
-int luaD_pretailcall (lua_State *L, CallInfo *ci, StkId func,
- int narg1, int delta) {
- unsigned status = LUA_MULTRET + 1;
- retry:
- switch (ttypetag(s2v(func))) {
- case LUA_VCCL: /* C closure */
- return precallC(L, func, status, clCvalue(s2v(func))->f);
- case LUA_VLCF: /* light C function */
- return precallC(L, func, status, fvalue(s2v(func)));
- case LUA_VLCL: { /* Lua function */
- Proto *p = clLvalue(s2v(func))->p;
- int fsize = p->maxstacksize; /* frame size */
- int nfixparams = p->numparams;
- int i;
- checkstackp(L, fsize - delta, func);
- ci->func.p -= delta; /* restore 'func' (if vararg) */
- for (i = 0; i < narg1; i++) /* move down function and arguments */
- setobjs2s(L, ci->func.p + i, func + i);
- func = ci->func.p; /* moved-down function */
- for (; narg1 <= nfixparams; narg1++)
- setnilvalue(s2v(func + narg1)); /* complete missing arguments */
- ci->top.p = func + 1 + fsize; /* top for new function */
- lua_assert(ci->top.p <= L->stack_last.p);
- ci->u.l.savedpc = p->code; /* starting point */
- ci->callstatus |= CIST_TAIL;
- L->top.p = func + narg1; /* set top */
- return -1;
- }
- default: { /* not a function */
- checkstackp(L, 1, func); /* space for metamethod */
- status = tryfuncTM(L, func, status); /* try '__call' metamethod */
- narg1++;
- goto retry; /* try again */
- }
- }
-}
-
-
-/*
-** Prepares the call to a function (C or Lua). For C functions, also do
-** the call. The function to be called is at '*func'. The arguments
-** are on the stack, right after the function. Returns the CallInfo
-** to be executed, if it was a Lua function. Otherwise (a C function)
-** returns NULL, with all the results on the stack, starting at the
-** original function position.
-*/
-CallInfo *luaD_precall (lua_State *L, StkId func, int nresults) {
- unsigned status = cast_uint(nresults + 1);
- lua_assert(status <= MAXRESULTS + 1);
- retry:
- switch (ttypetag(s2v(func))) {
- case LUA_VCCL: /* C closure */
- precallC(L, func, status, clCvalue(s2v(func))->f);
- return NULL;
- case LUA_VLCF: /* light C function */
- precallC(L, func, status, fvalue(s2v(func)));
- return NULL;
- case LUA_VLCL: { /* Lua function */
- CallInfo *ci;
- Proto *p = clLvalue(s2v(func))->p;
- int narg = cast_int(L->top.p - func) - 1; /* number of real arguments */
- int nfixparams = p->numparams;
- int fsize = p->maxstacksize; /* frame size */
- checkstackp(L, fsize, func);
- L->ci = ci = prepCallInfo(L, func, status, func + 1 + fsize);
- ci->u.l.savedpc = p->code; /* starting point */
- for (; narg < nfixparams; narg++)
- setnilvalue(s2v(L->top.p++)); /* complete missing arguments */
- lua_assert(ci->top.p <= L->stack_last.p);
- return ci;
- }
- default: { /* not a function */
- checkstackp(L, 1, func); /* space for metamethod */
- status = tryfuncTM(L, func, status); /* try '__call' metamethod */
- goto retry; /* try again with metamethod */
- }
- }
-}
-
-
-/*
-** Call a function (C or Lua) through C. 'inc' can be 1 (increment
-** number of recursive invocations in the C stack) or nyci (the same
-** plus increment number of non-yieldable calls).
-** This function can be called with some use of EXTRA_STACK, so it should
-** check the stack before doing anything else. 'luaD_precall' already
-** does that.
-*/
-l_sinline void ccall (lua_State *L, StkId func, int nResults, l_uint32 inc) {
- CallInfo *ci;
- L->nCcalls += inc;
- if (l_unlikely(getCcalls(L) >= LUAI_MAXCCALLS)) {
- checkstackp(L, 0, func); /* free any use of EXTRA_STACK */
- luaE_checkcstack(L);
- }
- if ((ci = luaD_precall(L, func, nResults)) != NULL) { /* Lua function? */
- ci->callstatus |= CIST_FRESH; /* mark that it is a "fresh" execute */
- luaV_execute(L, ci); /* call it */
- }
- L->nCcalls -= inc;
-}
-
-
-/*
-** External interface for 'ccall'
-*/
-void luaD_call (lua_State *L, StkId func, int nResults) {
- ccall(L, func, nResults, 1);
-}
-
-
-/*
-** Similar to 'luaD_call', but does not allow yields during the call.
-*/
-void luaD_callnoyield (lua_State *L, StkId func, int nResults) {
- ccall(L, func, nResults, nyci);
-}
-
-
-/*
-** Finish the job of 'lua_pcallk' after it was interrupted by an yield.
-** (The caller, 'finishCcall', does the final call to 'adjustresults'.)
-** The main job is to complete the 'luaD_pcall' called by 'lua_pcallk'.
-** If a '__close' method yields here, eventually control will be back
-** to 'finishCcall' (when that '__close' method finally returns) and
-** 'finishpcallk' will run again and close any still pending '__close'
-** methods. Similarly, if a '__close' method errs, 'precover' calls
-** 'unroll' which calls ''finishCcall' and we are back here again, to
-** close any pending '__close' methods.
-** Note that, up to the call to 'luaF_close', the corresponding
-** 'CallInfo' is not modified, so that this repeated run works like the
-** first one (except that it has at least one less '__close' to do). In
-** particular, field CIST_RECST preserves the error status across these
-** multiple runs, changing only if there is a new error.
-*/
-static TStatus finishpcallk (lua_State *L, CallInfo *ci) {
- TStatus status = getcistrecst(ci); /* get original status */
- if (l_likely(status == LUA_OK)) /* no error? */
- status = LUA_YIELD; /* was interrupted by an yield */
- else { /* error */
- StkId func = restorestack(L, ci->u2.funcidx);
- L->allowhook = getoah(ci); /* restore 'allowhook' */
- func = luaF_close(L, func, status, 1); /* can yield or raise an error */
- luaD_seterrorobj(L, status, func);
- luaD_shrinkstack(L); /* restore stack size in case of overflow */
- setcistrecst(ci, LUA_OK); /* clear original status */
- }
- ci->callstatus &= ~CIST_YPCALL;
- L->errfunc = ci->u.c.old_errfunc;
- /* if it is here, there were errors or yields; unlike 'lua_pcallk',
- do not change status */
- return status;
-}
-
-
-/*
-** Completes the execution of a C function interrupted by an yield.
-** The interruption must have happened while the function was either
-** closing its tbc variables in 'moveresults' or executing
-** 'lua_callk'/'lua_pcallk'. In the first case, it just redoes
-** 'luaD_poscall'. In the second case, the call to 'finishpcallk'
-** finishes the interrupted execution of 'lua_pcallk'. After that, it
-** calls the continuation of the interrupted function and finally it
-** completes the job of the 'luaD_call' that called the function. In
-** the call to 'adjustresults', we do not know the number of results
-** of the function called by 'lua_callk'/'lua_pcallk', so we are
-** conservative and use LUA_MULTRET (always adjust).
-*/
-static void finishCcall (lua_State *L, CallInfo *ci) {
- int n; /* actual number of results from C function */
- if (ci->callstatus & CIST_CLSRET) { /* was closing TBC variable? */
- lua_assert(ci->callstatus & CIST_TBC);
- n = ci->u2.nres; /* just redo 'luaD_poscall' */
- /* don't need to reset CIST_CLSRET, as it will be set again anyway */
- }
- else {
- TStatus status = LUA_YIELD; /* default if there were no errors */
- lua_KFunction kf = ci->u.c.k; /* continuation function */
- /* must have a continuation and must be able to call it */
- lua_assert(kf != NULL && yieldable(L));
- if (ci->callstatus & CIST_YPCALL) /* was inside a 'lua_pcallk'? */
- status = finishpcallk(L, ci); /* finish it */
- adjustresults(L, LUA_MULTRET); /* finish 'lua_callk' */
- lua_unlock(L);
- n = (*kf)(L, APIstatus(status), ci->u.c.ctx); /* call continuation */
- lua_lock(L);
- api_checknelems(L, n);
- }
- luaD_poscall(L, ci, n); /* finish 'luaD_call' */
-}
-
-
-/*
-** Executes "full continuation" (everything in the stack) of a
-** previously interrupted coroutine until the stack is empty (or another
-** interruption long-jumps out of the loop).
-*/
-static void unroll (lua_State *L, void *ud) {
- CallInfo *ci;
- UNUSED(ud);
- while ((ci = L->ci) != &L->base_ci) { /* something in the stack */
- if (!isLua(ci)) /* C function? */
- finishCcall(L, ci); /* complete its execution */
- else { /* Lua function */
- luaV_finishOp(L); /* finish interrupted instruction */
- luaV_execute(L, ci); /* execute down to higher C 'boundary' */
- }
- }
-}
-
-
-/*
-** Try to find a suspended protected call (a "recover point") for the
-** given thread.
-*/
-static CallInfo *findpcall (lua_State *L) {
- CallInfo *ci;
- for (ci = L->ci; ci != NULL; ci = ci->previous) { /* search for a pcall */
- if (ci->callstatus & CIST_YPCALL)
- return ci;
- }
- return NULL; /* no pending pcall */
-}
-
-
-/*
-** Signal an error in the call to 'lua_resume', not in the execution
-** of the coroutine itself. (Such errors should not be handled by any
-** coroutine error handler and should not kill the coroutine.)
-*/
-static int resume_error (lua_State *L, const char *msg, int narg) {
- api_checkpop(L, narg);
- L->top.p -= narg; /* remove args from the stack */
- setsvalue2s(L, L->top.p, luaS_new(L, msg)); /* push error message */
- api_incr_top(L);
- lua_unlock(L);
- return LUA_ERRRUN;
-}
-
-
-/*
-** Do the work for 'lua_resume' in protected mode. Most of the work
-** depends on the status of the coroutine: initial state, suspended
-** inside a hook, or regularly suspended (optionally with a continuation
-** function), plus erroneous cases: non-suspended coroutine or dead
-** coroutine.
-*/
-static void resume (lua_State *L, void *ud) {
- int n = *(cast(int*, ud)); /* number of arguments */
- StkId firstArg = L->top.p - n; /* first argument */
- CallInfo *ci = L->ci;
- if (L->status == LUA_OK) /* starting a coroutine? */
- ccall(L, firstArg - 1, LUA_MULTRET, 0); /* just call its body */
- else { /* resuming from previous yield */
- lua_assert(L->status == LUA_YIELD);
- L->status = LUA_OK; /* mark that it is running (again) */
- if (isLua(ci)) { /* yielded inside a hook? */
- /* undo increment made by 'luaG_traceexec': instruction was not
- executed yet */
- lua_assert(ci->callstatus & CIST_HOOKYIELD);
- ci->u.l.savedpc--;
- L->top.p = firstArg; /* discard arguments */
- luaV_execute(L, ci); /* just continue running Lua code */
- }
- else { /* 'common' yield */
- if (ci->u.c.k != NULL) { /* does it have a continuation function? */
- lua_unlock(L);
- n = (*ci->u.c.k)(L, LUA_YIELD, ci->u.c.ctx); /* call continuation */
- lua_lock(L);
- api_checknelems(L, n);
- }
- luaD_poscall(L, ci, n); /* finish 'luaD_call' */
- }
- unroll(L, NULL); /* run continuation */
- }
-}
-
-
-/*
-** Unrolls a coroutine in protected mode while there are recoverable
-** errors, that is, errors inside a protected call. (Any error
-** interrupts 'unroll', and this loop protects it again so it can
-** continue.) Stops with a normal end (status == LUA_OK), an yield
-** (status == LUA_YIELD), or an unprotected error ('findpcall' doesn't
-** find a recover point).
-*/
-static TStatus precover (lua_State *L, TStatus status) {
- CallInfo *ci;
- while (errorstatus(status) && (ci = findpcall(L)) != NULL) {
- L->ci = ci; /* go down to recovery functions */
- setcistrecst(ci, status); /* status to finish 'pcall' */
- status = luaD_rawrunprotected(L, unroll, NULL);
- }
- return status;
-}
-
-
-LUA_API int lua_resume (lua_State *L, lua_State *from, int nargs,
- int *nresults) {
- TStatus status;
- lua_lock(L);
- if (L->status == LUA_OK) { /* may be starting a coroutine */
- if (L->ci != &L->base_ci) /* not in base level? */
- return resume_error(L, "cannot resume non-suspended coroutine", nargs);
- else if (L->top.p - (L->ci->func.p + 1) == nargs) /* no function? */
- return resume_error(L, "cannot resume dead coroutine", nargs);
- }
- else if (L->status != LUA_YIELD) /* ended with errors? */
- return resume_error(L, "cannot resume dead coroutine", nargs);
- L->nCcalls = (from) ? getCcalls(from) : 0;
- if (getCcalls(L) >= LUAI_MAXCCALLS)
- return resume_error(L, "C stack overflow", nargs);
- L->nCcalls++;
- luai_userstateresume(L, nargs);
- api_checkpop(L, (L->status == LUA_OK) ? nargs + 1 : nargs);
- status = luaD_rawrunprotected(L, resume, &nargs);
- /* continue running after recoverable errors */
- status = precover(L, status);
- if (l_likely(!errorstatus(status)))
- lua_assert(status == L->status); /* normal end or yield */
- else { /* unrecoverable error */
- L->status = status; /* mark thread as 'dead' */
- luaD_seterrorobj(L, status, L->top.p); /* push error message */
- L->ci->top.p = L->top.p;
- }
- *nresults = (status == LUA_YIELD) ? L->ci->u2.nyield
- : cast_int(L->top.p - (L->ci->func.p + 1));
- lua_unlock(L);
- return APIstatus(status);
-}
-
-
-LUA_API int lua_isyieldable (lua_State *L) {
- return yieldable(L);
-}
-
-
-LUA_API int lua_yieldk (lua_State *L, int nresults, lua_KContext ctx,
- lua_KFunction k) {
- CallInfo *ci;
- luai_userstateyield(L, nresults);
- lua_lock(L);
- ci = L->ci;
- api_checkpop(L, nresults);
- if (l_unlikely(!yieldable(L))) {
- if (L != mainthread(G(L)))
- luaG_runerror(L, "attempt to yield across a C-call boundary");
- else
- luaG_runerror(L, "attempt to yield from outside a coroutine");
- }
- L->status = LUA_YIELD;
- ci->u2.nyield = nresults; /* save number of results */
- if (isLua(ci)) { /* inside a hook? */
- lua_assert(!isLuacode(ci));
- api_check(L, nresults == 0, "hooks cannot yield values");
- api_check(L, k == NULL, "hooks cannot continue after yielding");
- }
- else {
- if ((ci->u.c.k = k) != NULL) /* is there a continuation? */
- ci->u.c.ctx = ctx; /* save context */
- luaD_throw(L, LUA_YIELD);
- }
- lua_assert(ci->callstatus & CIST_HOOKED); /* must be inside a hook */
- lua_unlock(L);
- return 0; /* return to 'luaD_hook' */
-}
-
-
-/*
-** Auxiliary structure to call 'luaF_close' in protected mode.
-*/
-struct CloseP {
- StkId level;
- TStatus status;
-};
-
-
-/*
-** Auxiliary function to call 'luaF_close' in protected mode.
-*/
-static void closepaux (lua_State *L, void *ud) {
- struct CloseP *pcl = cast(struct CloseP *, ud);
- luaF_close(L, pcl->level, pcl->status, 0);
-}
-
-
-/*
-** Calls 'luaF_close' in protected mode. Return the original status
-** or, in case of errors, the new status.
-*/
-TStatus luaD_closeprotected (lua_State *L, ptrdiff_t level, TStatus status) {
- CallInfo *old_ci = L->ci;
- lu_byte old_allowhooks = L->allowhook;
- for (;;) { /* keep closing upvalues until no more errors */
- struct CloseP pcl;
- pcl.level = restorestack(L, level); pcl.status = status;
- status = luaD_rawrunprotected(L, &closepaux, &pcl);
- if (l_likely(status == LUA_OK)) /* no more errors? */
- return pcl.status;
- else { /* an error occurred; restore saved state and repeat */
- L->ci = old_ci;
- L->allowhook = old_allowhooks;
- }
- }
-}
-
-
-/*
-** Call the C function 'func' in protected mode, restoring basic
-** thread information ('allowhook', etc.) and in particular
-** its stack level in case of errors.
-*/
-TStatus luaD_pcall (lua_State *L, Pfunc func, void *u, ptrdiff_t old_top,
- ptrdiff_t ef) {
- TStatus status;
- CallInfo *old_ci = L->ci;
- lu_byte old_allowhooks = L->allowhook;
- ptrdiff_t old_errfunc = L->errfunc;
- L->errfunc = ef;
- status = luaD_rawrunprotected(L, func, u);
- if (l_unlikely(status != LUA_OK)) { /* an error occurred? */
- L->ci = old_ci;
- L->allowhook = old_allowhooks;
- status = luaD_closeprotected(L, old_top, status);
- luaD_seterrorobj(L, status, restorestack(L, old_top));
- luaD_shrinkstack(L); /* restore stack size in case of overflow */
- }
- L->errfunc = old_errfunc;
- return status;
-}
-
-
-
-/*
-** Execute a protected parser.
-*/
-struct SParser { /* data to 'f_parser' */
- ZIO *z;
- Mbuffer buff; /* dynamic structure used by the scanner */
- Dyndata dyd; /* dynamic structures used by the parser */
- const char *mode;
- const char *name;
-};
-
-
-static void checkmode (lua_State *L, const char *mode, const char *x) {
- if (strchr(mode, x[0]) == NULL) {
- luaO_pushfstring(L,
- "attempt to load a %s chunk (mode is '%s')", x, mode);
- luaD_throw(L, LUA_ERRSYNTAX);
- }
-}
-
-
-static void f_parser (lua_State *L, void *ud) {
- LClosure *cl;
- struct SParser *p = cast(struct SParser *, ud);
- const char *mode = p->mode ? p->mode : "bt";
- int c = zgetc(p->z); /* read first character */
- if (c == LUA_SIGNATURE[0]) {
- int fixed = 0;
- if (strchr(mode, 'B') != NULL)
- fixed = 1;
- else
- checkmode(L, mode, "binary");
- cl = luaU_undump(L, p->z, p->name, fixed);
- }
- else {
- checkmode(L, mode, "text");
- cl = luaY_parser(L, p->z, &p->buff, &p->dyd, p->name, c);
- }
- lua_assert(cl->nupvalues == cl->p->sizeupvalues);
- luaF_initupvals(L, cl);
-}
-
-
-TStatus luaD_protectedparser (lua_State *L, ZIO *z, const char *name,
- const char *mode) {
- struct SParser p;
- TStatus status;
- incnny(L); /* cannot yield during parsing */
- p.z = z; p.name = name; p.mode = mode;
- p.dyd.actvar.arr = NULL; p.dyd.actvar.size = 0;
- p.dyd.gt.arr = NULL; p.dyd.gt.size = 0;
- p.dyd.label.arr = NULL; p.dyd.label.size = 0;
- luaZ_initbuffer(L, &p.buff);
- status = luaD_pcall(L, f_parser, &p, savestack(L, L->top.p), L->errfunc);
- luaZ_freebuffer(L, &p.buff);
- luaM_freearray(L, p.dyd.actvar.arr, cast_sizet(p.dyd.actvar.size));
- luaM_freearray(L, p.dyd.gt.arr, cast_sizet(p.dyd.gt.size));
- luaM_freearray(L, p.dyd.label.arr, cast_sizet(p.dyd.label.size));
- decnny(L);
- return status;
-}
-
-
diff --git a/ldo.h b/ldo.h
deleted file mode 100644
index b64729541c..0000000000
--- a/ldo.h
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
-** $Id: ldo.h $
-** Stack and Call structure of Lua
-** See Copyright Notice in lua.h
-*/
-
-#ifndef ldo_h
-#define ldo_h
-
-
-#include "llimits.h"
-#include "lobject.h"
-#include "lstate.h"
-#include "lzio.h"
-
-
-/*
-** Macro to check stack size and grow stack if needed. Parameters
-** 'pre'/'pos' allow the macro to preserve a pointer into the
-** stack across reallocations, doing the work only when needed.
-** It also allows the running of one GC step when the stack is
-** reallocated.
-** 'condmovestack' is used in heavy tests to force a stack reallocation
-** at every check.
-*/
-
-#if !defined(HARDSTACKTESTS)
-#define condmovestack(L,pre,pos) ((void)0)
-#else
-/* realloc stack keeping its size */
-#define condmovestack(L,pre,pos) \
- { int sz_ = stacksize(L); pre; luaD_reallocstack((L), sz_, 0); pos; }
-#endif
-
-#define luaD_checkstackaux(L,n,pre,pos) \
- if (l_unlikely(L->stack_last.p - L->top.p <= (n))) \
- { pre; luaD_growstack(L, n, 1); pos; } \
- else { condmovestack(L,pre,pos); }
-
-/* In general, 'pre'/'pos' are empty (nothing to save) */
-#define luaD_checkstack(L,n) luaD_checkstackaux(L,n,(void)0,(void)0)
-
-
-
-#define savestack(L,pt) (cast_charp(pt) - cast_charp(L->stack.p))
-#define restorestack(L,n) cast(StkId, cast_charp(L->stack.p) + (n))
-
-
-/* macro to check stack size, preserving 'p' */
-#define checkstackp(L,n,p) \
- luaD_checkstackaux(L, n, \
- ptrdiff_t t__ = savestack(L, p), /* save 'p' */ \
- p = restorestack(L, t__)) /* 'pos' part: restore 'p' */
-
-
-/*
-** Maximum depth for nested C calls, syntactical nested non-terminals,
-** and other features implemented through recursion in C. (Value must
-** fit in a 16-bit unsigned integer. It must also be compatible with
-** the size of the C stack.)
-*/
-#if !defined(LUAI_MAXCCALLS)
-#define LUAI_MAXCCALLS 200
-#endif
-
-
-/* type of protected functions, to be ran by 'runprotected' */
-typedef void (*Pfunc) (lua_State *L, void *ud);
-
-LUAI_FUNC l_noret luaD_errerr (lua_State *L);
-LUAI_FUNC void luaD_seterrorobj (lua_State *L, TStatus errcode, StkId oldtop);
-LUAI_FUNC TStatus luaD_protectedparser (lua_State *L, ZIO *z,
- const char *name,
- const char *mode);
-LUAI_FUNC void luaD_hook (lua_State *L, int event, int line,
- int fTransfer, int nTransfer);
-LUAI_FUNC void luaD_hookcall (lua_State *L, CallInfo *ci);
-LUAI_FUNC int luaD_pretailcall (lua_State *L, CallInfo *ci, StkId func,
- int narg1, int delta);
-LUAI_FUNC CallInfo *luaD_precall (lua_State *L, StkId func, int nResults);
-LUAI_FUNC void luaD_call (lua_State *L, StkId func, int nResults);
-LUAI_FUNC void luaD_callnoyield (lua_State *L, StkId func, int nResults);
-LUAI_FUNC TStatus luaD_closeprotected (lua_State *L, ptrdiff_t level,
- TStatus status);
-LUAI_FUNC TStatus luaD_pcall (lua_State *L, Pfunc func, void *u,
- ptrdiff_t oldtop, ptrdiff_t ef);
-LUAI_FUNC void luaD_poscall (lua_State *L, CallInfo *ci, int nres);
-LUAI_FUNC int luaD_reallocstack (lua_State *L, int newsize, int raiseerror);
-LUAI_FUNC int luaD_growstack (lua_State *L, int n, int raiseerror);
-LUAI_FUNC void luaD_shrinkstack (lua_State *L);
-LUAI_FUNC void luaD_inctop (lua_State *L);
-LUAI_FUNC int luaD_checkminstack (lua_State *L);
-
-LUAI_FUNC l_noret luaD_throw (lua_State *L, TStatus errcode);
-LUAI_FUNC l_noret luaD_throwbaselevel (lua_State *L, TStatus errcode);
-LUAI_FUNC TStatus luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud);
-
-#endif
-
diff --git a/ldump.c b/ldump.c
deleted file mode 100644
index 5795788922..0000000000
--- a/ldump.c
+++ /dev/null
@@ -1,307 +0,0 @@
-/*
-** $Id: ldump.c $
-** save precompiled Lua chunks
-** See Copyright Notice in lua.h
-*/
-
-#define ldump_c
-#define LUA_CORE
-
-#include "lprefix.h"
-
-
-#include
-#include
-
-#include "lua.h"
-
-#include "lapi.h"
-#include "lgc.h"
-#include "lobject.h"
-#include "lstate.h"
-#include "ltable.h"
-#include "lundump.h"
-
-
-typedef struct {
- lua_State *L;
- lua_Writer writer;
- void *data;
- size_t offset; /* current position relative to beginning of dump */
- int strip;
- int status;
- Table *h; /* table to track saved strings */
- lua_Unsigned nstr; /* counter for counting saved strings */
-} DumpState;
-
-
-/*
-** All high-level dumps go through dumpVector; you can change it to
-** change the endianness of the result
-*/
-#define dumpVector(D,v,n) dumpBlock(D,v,(n)*sizeof((v)[0]))
-
-#define dumpLiteral(D, s) dumpBlock(D,s,sizeof(s) - sizeof(char))
-
-
-/*
-** Dump the block of memory pointed by 'b' with given 'size'.
-** 'b' should not be NULL, except for the last call signaling the end
-** of the dump.
-*/
-static void dumpBlock (DumpState *D, const void *b, size_t size) {
- if (D->status == 0) { /* do not write anything after an error */
- lua_unlock(D->L);
- D->status = (*D->writer)(D->L, b, size, D->data);
- lua_lock(D->L);
- D->offset += size;
- }
-}
-
-
-/*
-** Dump enough zeros to ensure that current position is a multiple of
-** 'align'.
-*/
-static void dumpAlign (DumpState *D, unsigned align) {
- unsigned padding = align - cast_uint(D->offset % align);
- if (padding < align) { /* padding == align means no padding */
- static lua_Integer paddingContent = 0;
- lua_assert(align <= sizeof(lua_Integer));
- dumpBlock(D, &paddingContent, padding);
- }
- lua_assert(D->offset % align == 0);
-}
-
-
-#define dumpVar(D,x) dumpVector(D,&x,1)
-
-
-static void dumpByte (DumpState *D, int y) {
- lu_byte x = (lu_byte)y;
- dumpVar(D, x);
-}
-
-
-/*
-** size for 'dumpVarint' buffer: each byte can store up to 7 bits.
-** (The "+6" rounds up the division.)
-*/
-#define DIBS ((l_numbits(lua_Unsigned) + 6) / 7)
-
-/*
-** Dumps an unsigned integer using the MSB Varint encoding
-*/
-static void dumpVarint (DumpState *D, lua_Unsigned x) {
- lu_byte buff[DIBS];
- unsigned n = 1;
- buff[DIBS - 1] = x & 0x7f; /* fill least-significant byte */
- while ((x >>= 7) != 0) /* fill other bytes in reverse order */
- buff[DIBS - (++n)] = cast_byte((x & 0x7f) | 0x80);
- dumpVector(D, buff + DIBS - n, n);
-}
-
-
-static void dumpSize (DumpState *D, size_t sz) {
- dumpVarint(D, cast(lua_Unsigned, sz));
-}
-
-
-static void dumpInt (DumpState *D, int x) {
- lua_assert(x >= 0);
- dumpVarint(D, cast_uint(x));
-}
-
-
-static void dumpNumber (DumpState *D, lua_Number x) {
- dumpVar(D, x);
-}
-
-
-/*
-** Signed integers are coded to keep small values small. (Coding -1 as
-** 0xfff...fff would use too many bytes to save a quite common value.)
-** A non-negative x is coded as 2x; a negative x is coded as -2x - 1.
-** (0 => 0; -1 => 1; 1 => 2; -2 => 3; 2 => 4; ...)
-*/
-static void dumpInteger (DumpState *D, lua_Integer x) {
- lua_Unsigned cx = (x >= 0) ? 2u * l_castS2U(x)
- : (2u * ~l_castS2U(x)) + 1;
- dumpVarint(D, cx);
-}
-
-
-/*
-** Dump a String. First dump its "size":
-** size==0 is followed by an index and means "reuse saved string with
-** that index"; index==0 means NULL.
-** size>=1 is followed by the string contents with real size==size-1 and
-** means that string, which will be saved with the next available index.
-** The real size does not include the ending '\0' (which is not dumped),
-** so adding 1 to it cannot overflow a size_t.
-*/
-static void dumpString (DumpState *D, TString *ts) {
- if (ts == NULL) {
- dumpVarint(D, 0); /* will "reuse" NULL */
- dumpVarint(D, 0); /* special index for NULL */
- }
- else {
- TValue idx;
- int tag = luaH_getstr(D->h, ts, &idx);
- if (!tagisempty(tag)) { /* string already saved? */
- dumpVarint(D, 0); /* reuse a saved string */
- dumpVarint(D, l_castS2U(ivalue(&idx))); /* index of saved string */
- }
- else { /* must write and save the string */
- TValue key, value; /* to save the string in the hash */
- size_t size;
- const char *s = getlstr(ts, size);
- dumpSize(D, size + 1);
- dumpVector(D, s, size + 1); /* include ending '\0' */
- D->nstr++; /* one more saved string */
- setsvalue(D->L, &key, ts); /* the string is the key */
- setivalue(&value, l_castU2S(D->nstr)); /* its index is the value */
- luaH_set(D->L, D->h, &key, &value); /* h[ts] = nstr */
- /* integer value does not need barrier */
- }
- }
-}
-
-
-static void dumpCode (DumpState *D, const Proto *f) {
- dumpInt(D, f->sizecode);
- dumpAlign(D, sizeof(f->code[0]));
- lua_assert(f->code != NULL);
- dumpVector(D, f->code, cast_uint(f->sizecode));
-}
-
-
-static void dumpFunction (DumpState *D, const Proto *f);
-
-static void dumpConstants (DumpState *D, const Proto *f) {
- int i;
- int n = f->sizek;
- dumpInt(D, n);
- for (i = 0; i < n; i++) {
- const TValue *o = &f->k[i];
- int tt = ttypetag(o);
- dumpByte(D, tt);
- switch (tt) {
- case LUA_VNUMFLT:
- dumpNumber(D, fltvalue(o));
- break;
- case LUA_VNUMINT:
- dumpInteger(D, ivalue(o));
- break;
- case LUA_VSHRSTR:
- case LUA_VLNGSTR:
- dumpString(D, tsvalue(o));
- break;
- default:
- lua_assert(tt == LUA_VNIL || tt == LUA_VFALSE || tt == LUA_VTRUE);
- }
- }
-}
-
-
-static void dumpProtos (DumpState *D, const Proto *f) {
- int i;
- int n = f->sizep;
- dumpInt(D, n);
- for (i = 0; i < n; i++)
- dumpFunction(D, f->p[i]);
-}
-
-
-static void dumpUpvalues (DumpState *D, const Proto *f) {
- int i, n = f->sizeupvalues;
- dumpInt(D, n);
- for (i = 0; i < n; i++) {
- dumpByte(D, f->upvalues[i].instack);
- dumpByte(D, f->upvalues[i].idx);
- dumpByte(D, f->upvalues[i].kind);
- }
-}
-
-
-static void dumpDebug (DumpState *D, const Proto *f) {
- int i, n;
- n = (D->strip) ? 0 : f->sizelineinfo;
- dumpInt(D, n);
- if (f->lineinfo != NULL)
- dumpVector(D, f->lineinfo, cast_uint(n));
- n = (D->strip) ? 0 : f->sizeabslineinfo;
- dumpInt(D, n);
- if (n > 0) {
- /* 'abslineinfo' is an array of structures of int's */
- dumpAlign(D, sizeof(int));
- dumpVector(D, f->abslineinfo, cast_uint(n));
- }
- n = (D->strip) ? 0 : f->sizelocvars;
- dumpInt(D, n);
- for (i = 0; i < n; i++) {
- dumpString(D, f->locvars[i].varname);
- dumpInt(D, f->locvars[i].startpc);
- dumpInt(D, f->locvars[i].endpc);
- }
- n = (D->strip) ? 0 : f->sizeupvalues;
- dumpInt(D, n);
- for (i = 0; i < n; i++)
- dumpString(D, f->upvalues[i].name);
-}
-
-
-static void dumpFunction (DumpState *D, const Proto *f) {
- dumpInt(D, f->linedefined);
- dumpInt(D, f->lastlinedefined);
- dumpByte(D, f->numparams);
- dumpByte(D, f->flag);
- dumpByte(D, f->maxstacksize);
- dumpCode(D, f);
- dumpConstants(D, f);
- dumpUpvalues(D, f);
- dumpProtos(D, f);
- dumpString(D, D->strip ? NULL : f->source);
- dumpDebug(D, f);
-}
-
-
-#define dumpNumInfo(D, tvar, value) \
- { tvar i = value; dumpByte(D, sizeof(tvar)); dumpVar(D, i); }
-
-
-static void dumpHeader (DumpState *D) {
- dumpLiteral(D, LUA_SIGNATURE);
- dumpByte(D, LUAC_VERSION);
- dumpByte(D, LUAC_FORMAT);
- dumpLiteral(D, LUAC_DATA);
- dumpNumInfo(D, int, LUAC_INT);
- dumpNumInfo(D, Instruction, LUAC_INST);
- dumpNumInfo(D, lua_Integer, LUAC_INT);
- dumpNumInfo(D, lua_Number, LUAC_NUM);
-}
-
-
-/*
-** dump Lua function as precompiled chunk
-*/
-int luaU_dump (lua_State *L, const Proto *f, lua_Writer w, void *data,
- int strip) {
- DumpState D;
- D.h = luaH_new(L); /* aux. table to keep strings already dumped */
- sethvalue2s(L, L->top.p, D.h); /* anchor it */
- L->top.p++;
- D.L = L;
- D.writer = w;
- D.offset = 0;
- D.data = data;
- D.strip = strip;
- D.status = 0;
- D.nstr = 0;
- dumpHeader(&D);
- dumpByte(&D, f->sizeupvalues);
- dumpFunction(&D, f);
- dumpBlock(&D, NULL, 0); /* signal end of dump */
- return D.status;
-}
-
diff --git a/lfunc.c b/lfunc.c
deleted file mode 100644
index b6fd9ceb55..0000000000
--- a/lfunc.c
+++ /dev/null
@@ -1,314 +0,0 @@
-/*
-** $Id: lfunc.c $
-** Auxiliary functions to manipulate prototypes and closures
-** See Copyright Notice in lua.h
-*/
-
-#define lfunc_c
-#define LUA_CORE
-
-#include "lprefix.h"
-
-
-#include
-
-#include "lua.h"
-
-#include "ldebug.h"
-#include "ldo.h"
-#include "lfunc.h"
-#include "lgc.h"
-#include "lmem.h"
-#include "lobject.h"
-#include "lstate.h"
-
-
-
-CClosure *luaF_newCclosure (lua_State *L, int nupvals) {
- GCObject *o = luaC_newobj(L, LUA_VCCL, sizeCclosure(nupvals));
- CClosure *c = gco2ccl(o);
- c->nupvalues = cast_byte(nupvals);
- return c;
-}
-
-
-LClosure *luaF_newLclosure (lua_State *L, int nupvals) {
- GCObject *o = luaC_newobj(L, LUA_VLCL, sizeLclosure(nupvals));
- LClosure *c = gco2lcl(o);
- c->p = NULL;
- c->nupvalues = cast_byte(nupvals);
- while (nupvals--) c->upvals[nupvals] = NULL;
- return c;
-}
-
-
-/*
-** fill a closure with new closed upvalues
-*/
-void luaF_initupvals (lua_State *L, LClosure *cl) {
- int i;
- for (i = 0; i < cl->nupvalues; i++) {
- GCObject *o = luaC_newobj(L, LUA_VUPVAL, sizeof(UpVal));
- UpVal *uv = gco2upv(o);
- uv->v.p = &uv->u.value; /* make it closed */
- setnilvalue(uv->v.p);
- cl->upvals[i] = uv;
- luaC_objbarrier(L, cl, uv);
- }
-}
-
-
-/*
-** Create a new upvalue at the given level, and link it to the list of
-** open upvalues of 'L' after entry 'prev'.
-**/
-static UpVal *newupval (lua_State *L, StkId level, UpVal **prev) {
- GCObject *o = luaC_newobj(L, LUA_VUPVAL, sizeof(UpVal));
- UpVal *uv = gco2upv(o);
- UpVal *next = *prev;
- uv->v.p = s2v(level); /* current value lives in the stack */
- uv->u.open.next = next; /* link it to list of open upvalues */
- uv->u.open.previous = prev;
- if (next)
- next->u.open.previous = &uv->u.open.next;
- *prev = uv;
- if (!isintwups(L)) { /* thread not in list of threads with upvalues? */
- L->twups = G(L)->twups; /* link it to the list */
- G(L)->twups = L;
- }
- return uv;
-}
-
-
-/*
-** Find and reuse, or create if it does not exist, an upvalue
-** at the given level.
-*/
-UpVal *luaF_findupval (lua_State *L, StkId level) {
- UpVal **pp = &L->openupval;
- UpVal *p;
- lua_assert(isintwups(L) || L->openupval == NULL);
- while ((p = *pp) != NULL && uplevel(p) >= level) { /* search for it */
- lua_assert(!isdead(G(L), p));
- if (uplevel(p) == level) /* corresponding upvalue? */
- return p; /* return it */
- pp = &p->u.open.next;
- }
- /* not found: create a new upvalue after 'pp' */
- return newupval(L, level, pp);
-}
-
-
-/*
-** Call closing method for object 'obj' with error object 'err'. The
-** boolean 'yy' controls whether the call is yieldable.
-** (This function assumes EXTRA_STACK.)
-*/
-static void callclosemethod (lua_State *L, TValue *obj, TValue *err, int yy) {
- StkId top = L->top.p;
- StkId func = top;
- const TValue *tm = luaT_gettmbyobj(L, obj, TM_CLOSE);
- setobj2s(L, top++, tm); /* will call metamethod... */
- setobj2s(L, top++, obj); /* with 'self' as the 1st argument */
- if (err != NULL) /* if there was an error... */
- setobj2s(L, top++, err); /* then error object will be 2nd argument */
- L->top.p = top; /* add function and arguments */
- if (yy)
- luaD_call(L, func, 0);
- else
- luaD_callnoyield(L, func, 0);
-}
-
-
-/*
-** Check whether object at given level has a close metamethod and raise
-** an error if not.
-*/
-static void checkclosemth (lua_State *L, StkId level) {
- const TValue *tm = luaT_gettmbyobj(L, s2v(level), TM_CLOSE);
- if (ttisnil(tm)) { /* no metamethod? */
- int idx = cast_int(level - L->ci->func.p); /* variable index */
- const char *vname = luaG_findlocal(L, L->ci, idx, NULL);
- if (vname == NULL) vname = "?";
- luaG_runerror(L, "variable '%s' got a non-closable value", vname);
- }
-}
-
-
-/*
-** Prepare and call a closing method.
-** If status is CLOSEKTOP, the call to the closing method will be pushed
-** at the top of the stack. Otherwise, values can be pushed right after
-** the 'level' of the upvalue being closed, as everything after that
-** won't be used again.
-*/
-static void prepcallclosemth (lua_State *L, StkId level, TStatus status,
- int yy) {
- TValue *uv = s2v(level); /* value being closed */
- TValue *errobj;
- switch (status) {
- case LUA_OK:
- L->top.p = level + 1; /* call will be at this level */
- /* FALLTHROUGH */
- case CLOSEKTOP: /* don't need to change top */
- errobj = NULL; /* no error object */
- break;
- default: /* 'luaD_seterrorobj' will set top to level + 2 */
- errobj = s2v(level + 1); /* error object goes after 'uv' */
- luaD_seterrorobj(L, status, level + 1); /* set error object */
- break;
- }
- callclosemethod(L, uv, errobj, yy);
-}
-
-
-/* Maximum value for deltas in 'tbclist' */
-#define MAXDELTA USHRT_MAX
-
-
-/*
-** Insert a variable in the list of to-be-closed variables.
-*/
-void luaF_newtbcupval (lua_State *L, StkId level) {
- lua_assert(level > L->tbclist.p);
- if (l_isfalse(s2v(level)))
- return; /* false doesn't need to be closed */
- checkclosemth(L, level); /* value must have a close method */
- while (cast_uint(level - L->tbclist.p) > MAXDELTA) {
- L->tbclist.p += MAXDELTA; /* create a dummy node at maximum delta */
- L->tbclist.p->tbclist.delta = 0;
- }
- level->tbclist.delta = cast(unsigned short, level - L->tbclist.p);
- L->tbclist.p = level;
-}
-
-
-void luaF_unlinkupval (UpVal *uv) {
- lua_assert(upisopen(uv));
- *uv->u.open.previous = uv->u.open.next;
- if (uv->u.open.next)
- uv->u.open.next->u.open.previous = uv->u.open.previous;
-}
-
-
-/*
-** Close all upvalues up to the given stack level.
-*/
-void luaF_closeupval (lua_State *L, StkId level) {
- UpVal *uv;
- while ((uv = L->openupval) != NULL && uplevel(uv) >= level) {
- TValue *slot = &uv->u.value; /* new position for value */
- lua_assert(uplevel(uv) < L->top.p);
- luaF_unlinkupval(uv); /* remove upvalue from 'openupval' list */
- setobj(L, slot, uv->v.p); /* move value to upvalue slot */
- uv->v.p = slot; /* now current value lives here */
- if (!iswhite(uv)) { /* neither white nor dead? */
- nw2black(uv); /* closed upvalues cannot be gray */
- luaC_barrier(L, uv, slot);
- }
- }
-}
-
-
-/*
-** Remove first element from the tbclist plus its dummy nodes.
-*/
-static void poptbclist (lua_State *L) {
- StkId tbc = L->tbclist.p;
- lua_assert(tbc->tbclist.delta > 0); /* first element cannot be dummy */
- tbc -= tbc->tbclist.delta;
- while (tbc > L->stack.p && tbc->tbclist.delta == 0)
- tbc -= MAXDELTA; /* remove dummy nodes */
- L->tbclist.p = tbc;
-}
-
-
-/*
-** Close all upvalues and to-be-closed variables up to the given stack
-** level. Return restored 'level'.
-*/
-StkId luaF_close (lua_State *L, StkId level, TStatus status, int yy) {
- ptrdiff_t levelrel = savestack(L, level);
- luaF_closeupval(L, level); /* first, close the upvalues */
- while (L->tbclist.p >= level) { /* traverse tbc's down to that level */
- StkId tbc = L->tbclist.p; /* get variable index */
- poptbclist(L); /* remove it from list */
- prepcallclosemth(L, tbc, status, yy); /* close variable */
- level = restorestack(L, levelrel);
- }
- return level;
-}
-
-
-Proto *luaF_newproto (lua_State *L) {
- GCObject *o = luaC_newobj(L, LUA_VPROTO, sizeof(Proto));
- Proto *f = gco2p(o);
- f->k = NULL;
- f->sizek = 0;
- f->p = NULL;
- f->sizep = 0;
- f->code = NULL;
- f->sizecode = 0;
- f->lineinfo = NULL;
- f->sizelineinfo = 0;
- f->abslineinfo = NULL;
- f->sizeabslineinfo = 0;
- f->upvalues = NULL;
- f->sizeupvalues = 0;
- f->numparams = 0;
- f->flag = 0;
- f->maxstacksize = 0;
- f->locvars = NULL;
- f->sizelocvars = 0;
- f->linedefined = 0;
- f->lastlinedefined = 0;
- f->source = NULL;
- return f;
-}
-
-
-lu_mem luaF_protosize (Proto *p) {
- lu_mem sz = cast(lu_mem, sizeof(Proto))
- + cast_uint(p->sizep) * sizeof(Proto*)
- + cast_uint(p->sizek) * sizeof(TValue)
- + cast_uint(p->sizelocvars) * sizeof(LocVar)
- + cast_uint(p->sizeupvalues) * sizeof(Upvaldesc);
- if (!(p->flag & PF_FIXED)) {
- sz += cast_uint(p->sizecode) * sizeof(Instruction);
- sz += cast_uint(p->sizelineinfo) * sizeof(lu_byte);
- sz += cast_uint(p->sizeabslineinfo) * sizeof(AbsLineInfo);
- }
- return sz;
-}
-
-
-void luaF_freeproto (lua_State *L, Proto *f) {
- if (!(f->flag & PF_FIXED)) {
- luaM_freearray(L, f->code, cast_sizet(f->sizecode));
- luaM_freearray(L, f->lineinfo, cast_sizet(f->sizelineinfo));
- luaM_freearray(L, f->abslineinfo, cast_sizet(f->sizeabslineinfo));
- }
- luaM_freearray(L, f->p, cast_sizet(f->sizep));
- luaM_freearray(L, f->k, cast_sizet(f->sizek));
- luaM_freearray(L, f->locvars, cast_sizet(f->sizelocvars));
- luaM_freearray(L, f->upvalues, cast_sizet(f->sizeupvalues));
- luaM_free(L, f);
-}
-
-
-/*
-** Look for n-th local variable at line 'line' in function 'func'.
-** Returns NULL if not found.
-*/
-const char *luaF_getlocalname (const Proto *f, int local_number, int pc) {
- int i;
- for (i = 0; isizelocvars && f->locvars[i].startpc <= pc; i++) {
- if (pc < f->locvars[i].endpc) { /* is variable active? */
- local_number--;
- if (local_number == 0)
- return getstr(f->locvars[i].varname);
- }
- }
- return NULL; /* not found */
-}
-
diff --git a/lfunc.h b/lfunc.h
deleted file mode 100644
index d6aad3a6df..0000000000
--- a/lfunc.h
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
-** $Id: lfunc.h $
-** Auxiliary functions to manipulate prototypes and closures
-** See Copyright Notice in lua.h
-*/
-
-#ifndef lfunc_h
-#define lfunc_h
-
-
-#include "lobject.h"
-
-
-#define sizeCclosure(n) \
- (offsetof(CClosure, upvalue) + sizeof(TValue) * cast_uint(n))
-
-#define sizeLclosure(n) \
- (offsetof(LClosure, upvals) + sizeof(UpVal *) * cast_uint(n))
-
-
-/* test whether thread is in 'twups' list */
-#define isintwups(L) (L->twups != L)
-
-
-/*
-** maximum number of upvalues in a closure (both C and Lua). (Value
-** must fit in a VM register.)
-*/
-#define MAXUPVAL 255
-
-
-#define upisopen(up) ((up)->v.p != &(up)->u.value)
-
-
-#define uplevel(up) check_exp(upisopen(up), cast(StkId, (up)->v.p))
-
-
-/*
-** maximum number of misses before giving up the cache of closures
-** in prototypes
-*/
-#define MAXMISS 10
-
-
-
-/* special status to close upvalues preserving the top of the stack */
-#define CLOSEKTOP (LUA_ERRERR + 1)
-
-
-LUAI_FUNC Proto *luaF_newproto (lua_State *L);
-LUAI_FUNC CClosure *luaF_newCclosure (lua_State *L, int nupvals);
-LUAI_FUNC LClosure *luaF_newLclosure (lua_State *L, int nupvals);
-LUAI_FUNC void luaF_initupvals (lua_State *L, LClosure *cl);
-LUAI_FUNC UpVal *luaF_findupval (lua_State *L, StkId level);
-LUAI_FUNC void luaF_newtbcupval (lua_State *L, StkId level);
-LUAI_FUNC void luaF_closeupval (lua_State *L, StkId level);
-LUAI_FUNC StkId luaF_close (lua_State *L, StkId level, TStatus status, int yy);
-LUAI_FUNC void luaF_unlinkupval (UpVal *uv);
-LUAI_FUNC lu_mem luaF_protosize (Proto *p);
-LUAI_FUNC void luaF_freeproto (lua_State *L, Proto *f);
-LUAI_FUNC const char *luaF_getlocalname (const Proto *func, int local_number,
- int pc);
-
-
-#endif
diff --git a/lgc.c b/lgc.c
deleted file mode 100644
index 0f89451c64..0000000000
--- a/lgc.c
+++ /dev/null
@@ -1,1804 +0,0 @@
-/*
-** $Id: lgc.c $
-** Garbage Collector
-** See Copyright Notice in lua.h
-*/
-
-#define lgc_c
-#define LUA_CORE
-
-#include "lprefix.h"
-
-#include
-
-
-#include "lua.h"
-
-#include "ldebug.h"
-#include "ldo.h"
-#include "lfunc.h"
-#include "lgc.h"
-#include "lmem.h"
-#include "lobject.h"
-#include "lstate.h"
-#include "lstring.h"
-#include "ltable.h"
-#include "ltm.h"
-
-
-/*
-** Maximum number of elements to sweep in each single step.
-** (Large enough to dissipate fixed overheads but small enough
-** to allow small steps for the collector.)
-*/
-#define GCSWEEPMAX 20
-
-
-/*
-** Cost (in work units) of running one finalizer.
-*/
-#define CWUFIN 10
-
-
-/* mask with all color bits */
-#define maskcolors (bitmask(BLACKBIT) | WHITEBITS)
-
-/* mask with all GC bits */
-#define maskgcbits (maskcolors | AGEBITS)
-
-
-/* macro to erase all color bits then set only the current white bit */
-#define makewhite(g,x) \
- (x->marked = cast_byte((x->marked & ~maskcolors) | luaC_white(g)))
-
-/* make an object gray (neither white nor black) */
-#define set2gray(x) resetbits(x->marked, maskcolors)
-
-
-/* make an object black (coming from any color) */
-#define set2black(x) \
- (x->marked = cast_byte((x->marked & ~WHITEBITS) | bitmask(BLACKBIT)))
-
-
-#define valiswhite(x) (iscollectable(x) && iswhite(gcvalue(x)))
-
-#define keyiswhite(n) (keyiscollectable(n) && iswhite(gckey(n)))
-
-
-/*
-** Protected access to objects in values
-*/
-#define gcvalueN(o) (iscollectable(o) ? gcvalue(o) : NULL)
-
-
-/*
-** Access to collectable objects in array part of tables
-*/
-#define gcvalarr(t,i) \
- ((*getArrTag(t,i) & BIT_ISCOLLECTABLE) ? getArrVal(t,i)->gc : NULL)
-
-
-#define markvalue(g,o) { checkliveness(mainthread(g),o); \
- if (valiswhite(o)) reallymarkobject(g,gcvalue(o)); }
-
-#define markkey(g, n) { if keyiswhite(n) reallymarkobject(g,gckey(n)); }
-
-#define markobject(g,t) { if (iswhite(t)) reallymarkobject(g, obj2gco(t)); }
-
-/*
-** mark an object that can be NULL (either because it is really optional,
-** or it was stripped as debug info, or inside an uncompleted structure)
-*/
-#define markobjectN(g,t) { if (t) markobject(g,t); }
-
-
-static void reallymarkobject (global_State *g, GCObject *o);
-static void atomic (lua_State *L);
-static void entersweep (lua_State *L);
-
-
-/*
-** {======================================================
-** Generic functions
-** =======================================================
-*/
-
-
-/*
-** one after last element in a hash array
-*/
-#define gnodelast(h) gnode(h, cast_sizet(sizenode(h)))
-
-
-static l_mem objsize (GCObject *o) {
- lu_mem res;
- switch (o->tt) {
- case LUA_VTABLE: {
- res = luaH_size(gco2t(o));
- break;
- }
- case LUA_VLCL: {
- LClosure *cl = gco2lcl(o);
- res = sizeLclosure(cl->nupvalues);
- break;
- }
- case LUA_VCCL: {
- CClosure *cl = gco2ccl(o);
- res = sizeCclosure(cl->nupvalues);
- break;
- }
- case LUA_VUSERDATA: {
- Udata *u = gco2u(o);
- res = sizeudata(u->nuvalue, u->len);
- break;
- }
- case LUA_VPROTO: {
- res = luaF_protosize(gco2p(o));
- break;
- }
- case LUA_VTHREAD: {
- res = luaE_threadsize(gco2th(o));
- break;
- }
- case LUA_VSHRSTR: {
- TString *ts = gco2ts(o);
- res = sizestrshr(cast_uint(ts->shrlen));
- break;
- }
- case LUA_VLNGSTR: {
- TString *ts = gco2ts(o);
- res = luaS_sizelngstr(ts->u.lnglen, ts->shrlen);
- break;
- }
- case LUA_VUPVAL: {
- res = sizeof(UpVal);
- break;
- }
- default: res = 0; lua_assert(0);
- }
- return cast(l_mem, res);
-}
-
-
-static GCObject **getgclist (GCObject *o) {
- switch (o->tt) {
- case LUA_VTABLE: return &gco2t(o)->gclist;
- case LUA_VLCL: return &gco2lcl(o)->gclist;
- case LUA_VCCL: return &gco2ccl(o)->gclist;
- case LUA_VTHREAD: return &gco2th(o)->gclist;
- case LUA_VPROTO: return &gco2p(o)->gclist;
- case LUA_VUSERDATA: {
- Udata *u = gco2u(o);
- lua_assert(u->nuvalue > 0);
- return &u->gclist;
- }
- default: lua_assert(0); return 0;
- }
-}
-
-
-/*
-** Link a collectable object 'o' with a known type into the list 'p'.
-** (Must be a macro to access the 'gclist' field in different types.)
-*/
-#define linkgclist(o,p) linkgclist_(obj2gco(o), &(o)->gclist, &(p))
-
-static void linkgclist_ (GCObject *o, GCObject **pnext, GCObject **list) {
- lua_assert(!isgray(o)); /* cannot be in a gray list */
- *pnext = *list;
- *list = o;
- set2gray(o); /* now it is */
-}
-
-
-/*
-** Link a generic collectable object 'o' into the list 'p'.
-*/
-#define linkobjgclist(o,p) linkgclist_(obj2gco(o), getgclist(o), &(p))
-
-
-
-/*
-** Clear keys for empty entries in tables. If entry is empty, mark its
-** entry as dead. This allows the collection of the key, but keeps its
-** entry in the table: its removal could break a chain and could break
-** a table traversal. Other places never manipulate dead keys, because
-** its associated empty value is enough to signal that the entry is
-** logically empty.
-*/
-static void clearkey (Node *n) {
- lua_assert(isempty(gval(n)));
- if (keyiscollectable(n))
- setdeadkey(n); /* unused key; remove it */
-}
-
-
-/*
-** tells whether a key or value can be cleared from a weak
-** table. Non-collectable objects are never removed from weak
-** tables. Strings behave as 'values', so are never removed too. for
-** other objects: if really collected, cannot keep them; for objects
-** being finalized, keep them in keys, but not in values
-*/
-static int iscleared (global_State *g, const GCObject *o) {
- if (o == NULL) return 0; /* non-collectable value */
- else if (novariant(o->tt) == LUA_TSTRING) {
- markobject(g, o); /* strings are 'values', so are never weak */
- return 0;
- }
- else return iswhite(o);
-}
-
-
-/*
-** Barrier that moves collector forward, that is, marks the white object
-** 'v' being pointed by the black object 'o'. In the generational
-** mode, 'v' must also become old, if 'o' is old; however, it cannot
-** be changed directly to OLD, because it may still point to non-old
-** objects. So, it is marked as OLD0. In the next cycle it will become
-** OLD1, and in the next it will finally become OLD (regular old). By
-** then, any object it points to will also be old. If called in the
-** incremental sweep phase, it clears the black object to white (sweep
-** it) to avoid other barrier calls for this same object. (That cannot
-** be done is generational mode, as its sweep does not distinguish
-** white from dead.)
-*/
-void luaC_barrier_ (lua_State *L, GCObject *o, GCObject *v) {
- global_State *g = G(L);
- lua_assert(isblack(o) && iswhite(v) && !isdead(g, v) && !isdead(g, o));
- if (keepinvariant(g)) { /* must keep invariant? */
- reallymarkobject(g, v); /* restore invariant */
- if (isold(o)) {
- lua_assert(!isold(v)); /* white object could not be old */
- setage(v, G_OLD0); /* restore generational invariant */
- }
- }
- else { /* sweep phase */
- lua_assert(issweepphase(g));
- if (g->gckind != KGC_GENMINOR) /* incremental mode? */
- makewhite(g, o); /* mark 'o' as white to avoid other barriers */
- }
-}
-
-
-/*
-** barrier that moves collector backward, that is, mark the black object
-** pointing to a white object as gray again.
-*/
-void luaC_barrierback_ (lua_State *L, GCObject *o) {
- global_State *g = G(L);
- lua_assert(isblack(o) && !isdead(g, o));
- lua_assert((g->gckind != KGC_GENMINOR)
- || (isold(o) && getage(o) != G_TOUCHED1));
- if (getage(o) == G_TOUCHED2) /* already in gray list? */
- set2gray(o); /* make it gray to become touched1 */
- else /* link it in 'grayagain' and paint it gray */
- linkobjgclist(o, g->grayagain);
- if (isold(o)) /* generational mode? */
- setage(o, G_TOUCHED1); /* touched in current cycle */
-}
-
-
-void luaC_fix (lua_State *L, GCObject *o) {
- global_State *g = G(L);
- lua_assert(g->allgc == o); /* object must be 1st in 'allgc' list! */
- set2gray(o); /* they will be gray forever */
- setage(o, G_OLD); /* and old forever */
- g->allgc = o->next; /* remove object from 'allgc' list */
- o->next = g->fixedgc; /* link it to 'fixedgc' list */
- g->fixedgc = o;
-}
-
-
-/*
-** create a new collectable object (with given type, size, and offset)
-** and link it to 'allgc' list.
-*/
-GCObject *luaC_newobjdt (lua_State *L, lu_byte tt, size_t sz, size_t offset) {
- global_State *g = G(L);
- char *p = cast_charp(luaM_newobject(L, novariant(tt), sz));
- GCObject *o = cast(GCObject *, p + offset);
- o->marked = luaC_white(g);
- o->tt = tt;
- o->next = g->allgc;
- g->allgc = o;
- return o;
-}
-
-
-/*
-** create a new collectable object with no offset.
-*/
-GCObject *luaC_newobj (lua_State *L, lu_byte tt, size_t sz) {
- return luaC_newobjdt(L, tt, sz, 0);
-}
-
-/* }====================================================== */
-
-
-
-/*
-** {======================================================
-** Mark functions
-** =======================================================
-*/
-
-
-/*
-** Mark an object. Userdata with no user values, strings, and closed
-** upvalues are visited and turned black here. Open upvalues are
-** already indirectly linked through their respective threads in the
-** 'twups' list, so they don't go to the gray list; nevertheless, they
-** are kept gray to avoid barriers, as their values will be revisited
-** by the thread or by 'remarkupvals'. Other objects are added to the
-** gray list to be visited (and turned black) later. Both userdata and
-** upvalues can call this function recursively, but this recursion goes
-** for at most two levels: An upvalue cannot refer to another upvalue
-** (only closures can), and a userdata's metatable must be a table.
-*/
-static void reallymarkobject (global_State *g, GCObject *o) {
- g->GCmarked += objsize(o);
- switch (o->tt) {
- case LUA_VSHRSTR:
- case LUA_VLNGSTR: {
- set2black(o); /* nothing to visit */
- break;
- }
- case LUA_VUPVAL: {
- UpVal *uv = gco2upv(o);
- if (upisopen(uv))
- set2gray(uv); /* open upvalues are kept gray */
- else
- set2black(uv); /* closed upvalues are visited here */
- markvalue(g, uv->v.p); /* mark its content */
- break;
- }
- case LUA_VUSERDATA: {
- Udata *u = gco2u(o);
- if (u->nuvalue == 0) { /* no user values? */
- markobjectN(g, u->metatable); /* mark its metatable */
- set2black(u); /* nothing else to mark */
- break;
- }
- /* else... */
- } /* FALLTHROUGH */
- case LUA_VLCL: case LUA_VCCL: case LUA_VTABLE:
- case LUA_VTHREAD: case LUA_VPROTO: {
- linkobjgclist(o, g->gray); /* to be visited later */
- break;
- }
- default: lua_assert(0); break;
- }
-}
-
-
-/*
-** mark metamethods for basic types
-*/
-static void markmt (global_State *g) {
- int i;
- for (i=0; i < LUA_NUMTYPES; i++)
- markobjectN(g, g->mt[i]);
-}
-
-
-/*
-** mark all objects in list of being-finalized
-*/
-static void markbeingfnz (global_State *g) {
- GCObject *o;
- for (o = g->tobefnz; o != NULL; o = o->next)
- markobject(g, o);
-}
-
-
-/*
-** For each non-marked thread, simulates a barrier between each open
-** upvalue and its value. (If the thread is collected, the value will be
-** assigned to the upvalue, but then it can be too late for the barrier
-** to act. The "barrier" does not need to check colors: A non-marked
-** thread must be young; upvalues cannot be older than their threads; so
-** any visited upvalue must be young too.) Also removes the thread from
-** the list, as it was already visited. Removes also threads with no
-** upvalues, as they have nothing to be checked. (If the thread gets an
-** upvalue later, it will be linked in the list again.)
-*/
-static void remarkupvals (global_State *g) {
- lua_State *thread;
- lua_State **p = &g->twups;
- while ((thread = *p) != NULL) {
- if (!iswhite(thread) && thread->openupval != NULL)
- p = &thread->twups; /* keep marked thread with upvalues in the list */
- else { /* thread is not marked or without upvalues */
- UpVal *uv;
- lua_assert(!isold(thread) || thread->openupval == NULL);
- *p = thread->twups; /* remove thread from the list */
- thread->twups = thread; /* mark that it is out of list */
- for (uv = thread->openupval; uv != NULL; uv = uv->u.open.next) {
- lua_assert(getage(uv) <= getage(thread));
- if (!iswhite(uv)) { /* upvalue already visited? */
- lua_assert(upisopen(uv) && isgray(uv));
- markvalue(g, uv->v.p); /* mark its value */
- }
- }
- }
- }
-}
-
-
-static void cleargraylists (global_State *g) {
- g->gray = g->grayagain = NULL;
- g->weak = g->allweak = g->ephemeron = NULL;
-}
-
-
-/*
-** mark root set and reset all gray lists, to start a new collection.
-** 'GCmarked' is initialized to count the total number of live bytes
-** during a cycle.
-*/
-static void restartcollection (global_State *g) {
- cleargraylists(g);
- g->GCmarked = 0;
- markobject(g, mainthread(g));
- markvalue(g, &g->l_registry);
- markmt(g);
- markbeingfnz(g); /* mark any finalizing object left from previous cycle */
-}
-
-/* }====================================================== */
-
-
-/*
-** {======================================================
-** Traverse functions
-** =======================================================
-*/
-
-
-/*
-** Check whether object 'o' should be kept in the 'grayagain' list for
-** post-processing by 'correctgraylist'. (It could put all old objects
-** in the list and leave all the work to 'correctgraylist', but it is
-** more efficient to avoid adding elements that will be removed.) Only
-** TOUCHED1 objects need to be in the list. TOUCHED2 doesn't need to go
-** back to a gray list, but then it must become OLD. (That is what
-** 'correctgraylist' does when it finds a TOUCHED2 object.)
-** This function is a no-op in incremental mode, as objects cannot be
-** marked as touched in that mode.
-*/
-static void genlink (global_State *g, GCObject *o) {
- lua_assert(isblack(o));
- if (getage(o) == G_TOUCHED1) { /* touched in this cycle? */
- linkobjgclist(o, g->grayagain); /* link it back in 'grayagain' */
- } /* everything else do not need to be linked back */
- else if (getage(o) == G_TOUCHED2)
- setage(o, G_OLD); /* advance age */
-}
-
-
-/*
-** Traverse a table with weak values and link it to proper list. During
-** propagate phase, keep it in 'grayagain' list, to be revisited in the
-** atomic phase. In the atomic phase, if table has any white value,
-** put it in 'weak' list, to be cleared; otherwise, call 'genlink'
-** to check table age in generational mode.
-*/
-static void traverseweakvalue (global_State *g, Table *h) {
- Node *n, *limit = gnodelast(h);
- /* if there is array part, assume it may have white values (it is not
- worth traversing it now just to check) */
- int hasclears = (h->asize > 0);
- for (n = gnode(h, 0); n < limit; n++) { /* traverse hash part */
- if (isempty(gval(n))) /* entry is empty? */
- clearkey(n); /* clear its key */
- else {
- lua_assert(!keyisnil(n));
- markkey(g, n);
- if (!hasclears && iscleared(g, gcvalueN(gval(n)))) /* a white value? */
- hasclears = 1; /* table will have to be cleared */
- }
- }
- if (g->gcstate == GCSpropagate)
- linkgclist(h, g->grayagain); /* must retraverse it in atomic phase */
- else if (hasclears)
- linkgclist(h, g->weak); /* has to be cleared later */
- else
- genlink(g, obj2gco(h));
-}
-
-
-/*
-** Traverse the array part of a table.
-*/
-static int traversearray (global_State *g, Table *h) {
- unsigned asize = h->asize;
- int marked = 0; /* true if some object is marked in this traversal */
- unsigned i;
- for (i = 0; i < asize; i++) {
- GCObject *o = gcvalarr(h, i);
- if (o != NULL && iswhite(o)) {
- marked = 1;
- reallymarkobject(g, o);
- }
- }
- return marked;
-}
-
-
-/*
-** Traverse an ephemeron table and link it to proper list. Returns true
-** iff any object was marked during this traversal (which implies that
-** convergence has to continue). During propagation phase, keep table
-** in 'grayagain' list, to be visited again in the atomic phase. In
-** the atomic phase, if table has any white->white entry, it has to
-** be revisited during ephemeron convergence (as that key may turn
-** black). Otherwise, if it has any white key, table has to be cleared
-** (in the atomic phase). In generational mode, some tables
-** must be kept in some gray list for post-processing; this is done
-** by 'genlink'.
-*/
-static int traverseephemeron (global_State *g, Table *h, int inv) {
- int hasclears = 0; /* true if table has white keys */
- int hasww = 0; /* true if table has entry "white-key -> white-value" */
- unsigned int i;
- unsigned int nsize = sizenode(h);
- int marked = traversearray(g, h); /* traverse array part */
- /* traverse hash part; if 'inv', traverse descending
- (see 'convergeephemerons') */
- for (i = 0; i < nsize; i++) {
- Node *n = inv ? gnode(h, nsize - 1 - i) : gnode(h, i);
- if (isempty(gval(n))) /* entry is empty? */
- clearkey(n); /* clear its key */
- else if (iscleared(g, gckeyN(n))) { /* key is not marked (yet)? */
- hasclears = 1; /* table must be cleared */
- if (valiswhite(gval(n))) /* value not marked yet? */
- hasww = 1; /* white-white entry */
- }
- else if (valiswhite(gval(n))) { /* value not marked yet? */
- marked = 1;
- reallymarkobject(g, gcvalue(gval(n))); /* mark it now */
- }
- }
- /* link table into proper list */
- if (g->gcstate == GCSpropagate)
- linkgclist(h, g->grayagain); /* must retraverse it in atomic phase */
- else if (hasww) /* table has white->white entries? */
- linkgclist(h, g->ephemeron); /* have to propagate again */
- else if (hasclears) /* table has white keys? */
- linkgclist(h, g->allweak); /* may have to clean white keys */
- else
- genlink(g, obj2gco(h)); /* check whether collector still needs to see it */
- return marked;
-}
-
-
-static void traversestrongtable (global_State *g, Table *h) {
- Node *n, *limit = gnodelast(h);
- traversearray(g, h);
- for (n = gnode(h, 0); n < limit; n++) { /* traverse hash part */
- if (isempty(gval(n))) /* entry is empty? */
- clearkey(n); /* clear its key */
- else {
- lua_assert(!keyisnil(n));
- markkey(g, n);
- markvalue(g, gval(n));
- }
- }
- genlink(g, obj2gco(h));
-}
-
-
-/*
-** (result & 1) iff weak values; (result & 2) iff weak keys.
-*/
-static int getmode (global_State *g, Table *h) {
- const TValue *mode = gfasttm(g, h->metatable, TM_MODE);
- if (mode == NULL || !ttisstring(mode))
- return 0; /* ignore non-string modes */
- else {
- const char *smode = getstr(tsvalue(mode));
- const char *weakkey = strchr(smode, 'k');
- const char *weakvalue = strchr(smode, 'v');
- return ((weakkey != NULL) << 1) | (weakvalue != NULL);
- }
-}
-
-
-static l_mem traversetable (global_State *g, Table *h) {
- markobjectN(g, h->metatable);
- switch (getmode(g, h)) {
- case 0: /* not weak */
- traversestrongtable(g, h);
- break;
- case 1: /* weak values */
- traverseweakvalue(g, h);
- break;
- case 2: /* weak keys */
- traverseephemeron(g, h, 0);
- break;
- case 3: /* all weak; nothing to traverse */
- if (g->gcstate == GCSpropagate)
- linkgclist(h, g->grayagain); /* must visit again its metatable */
- else
- linkgclist(h, g->allweak); /* must clear collected entries */
- break;
- }
- return cast(l_mem, 1 + 2*sizenode(h) + h->asize);
-}
-
-
-static l_mem traverseudata (global_State *g, Udata *u) {
- int i;
- markobjectN(g, u->metatable); /* mark its metatable */
- for (i = 0; i < u->nuvalue; i++)
- markvalue(g, &u->uv[i].uv);
- genlink(g, obj2gco(u));
- return 1 + u->nuvalue;
-}
-
-
-/*
-** Traverse a prototype. (While a prototype is being build, its
-** arrays can be larger than needed; the extra slots are filled with
-** NULL, so the use of 'markobjectN')
-*/
-static l_mem traverseproto (global_State *g, Proto *f) {
- int i;
- markobjectN(g, f->source);
- for (i = 0; i < f->sizek; i++) /* mark literals */
- markvalue(g, &f->k[i]);
- for (i = 0; i < f->sizeupvalues; i++) /* mark upvalue names */
- markobjectN(g, f->upvalues[i].name);
- for (i = 0; i < f->sizep; i++) /* mark nested protos */
- markobjectN(g, f->p[i]);
- for (i = 0; i < f->sizelocvars; i++) /* mark local-variable names */
- markobjectN(g, f->locvars[i].varname);
- return 1 + f->sizek + f->sizeupvalues + f->sizep + f->sizelocvars;
-}
-
-
-static l_mem traverseCclosure (global_State *g, CClosure *cl) {
- int i;
- for (i = 0; i < cl->nupvalues; i++) /* mark its upvalues */
- markvalue(g, &cl->upvalue[i]);
- return 1 + cl->nupvalues;
-}
-
-/*
-** Traverse a Lua closure, marking its prototype and its upvalues.
-** (Both can be NULL while closure is being created.)
-*/
-static l_mem traverseLclosure (global_State *g, LClosure *cl) {
- int i;
- markobjectN(g, cl->p); /* mark its prototype */
- for (i = 0; i < cl->nupvalues; i++) { /* visit its upvalues */
- UpVal *uv = cl->upvals[i];
- markobjectN(g, uv); /* mark upvalue */
- }
- return 1 + cl->nupvalues;
-}
-
-
-/*
-** Traverse a thread, marking the elements in the stack up to its top
-** and cleaning the rest of the stack in the final traversal. That
-** ensures that the entire stack have valid (non-dead) objects.
-** Threads have no barriers. In gen. mode, old threads must be visited
-** at every cycle, because they might point to young objects. In inc.
-** mode, the thread can still be modified before the end of the cycle,
-** and therefore it must be visited again in the atomic phase. To ensure
-** these visits, threads must return to a gray list if they are not new
-** (which can only happen in generational mode) or if the traverse is in
-** the propagate phase (which can only happen in incremental mode).
-*/
-static l_mem traversethread (global_State *g, lua_State *th) {
- UpVal *uv;
- StkId o = th->stack.p;
- if (isold(th) || g->gcstate == GCSpropagate)
- linkgclist(th, g->grayagain); /* insert into 'grayagain' list */
- if (o == NULL)
- return 0; /* stack not completely built yet */
- lua_assert(g->gcstate == GCSatomic ||
- th->openupval == NULL || isintwups(th));
- for (; o < th->top.p; o++) /* mark live elements in the stack */
- markvalue(g, s2v(o));
- for (uv = th->openupval; uv != NULL; uv = uv->u.open.next)
- markobject(g, uv); /* open upvalues cannot be collected */
- if (g->gcstate == GCSatomic) { /* final traversal? */
- if (!g->gcemergency)
- luaD_shrinkstack(th); /* do not change stack in emergency cycle */
- for (o = th->top.p; o < th->stack_last.p + EXTRA_STACK; o++)
- setnilvalue(s2v(o)); /* clear dead stack slice */
- /* 'remarkupvals' may have removed thread from 'twups' list */
- if (!isintwups(th) && th->openupval != NULL) {
- th->twups = g->twups; /* link it back to the list */
- g->twups = th;
- }
- }
- return 1 + (th->top.p - th->stack.p);
-}
-
-
-/*
-** traverse one gray object, turning it to black. Return an estimate
-** of the number of slots traversed.
-*/
-static l_mem propagatemark (global_State *g) {
- GCObject *o = g->gray;
- nw2black(o);
- g->gray = *getgclist(o); /* remove from 'gray' list */
- switch (o->tt) {
- case LUA_VTABLE: return traversetable(g, gco2t(o));
- case LUA_VUSERDATA: return traverseudata(g, gco2u(o));
- case LUA_VLCL: return traverseLclosure(g, gco2lcl(o));
- case LUA_VCCL: return traverseCclosure(g, gco2ccl(o));
- case LUA_VPROTO: return traverseproto(g, gco2p(o));
- case LUA_VTHREAD: return traversethread(g, gco2th(o));
- default: lua_assert(0); return 0;
- }
-}
-
-
-static void propagateall (global_State *g) {
- while (g->gray)
- propagatemark(g);
-}
-
-
-/*
-** Traverse all ephemeron tables propagating marks from keys to values.
-** Repeat until it converges, that is, nothing new is marked. 'dir'
-** inverts the direction of the traversals, trying to speed up
-** convergence on chains in the same table.
-*/
-static void convergeephemerons (global_State *g) {
- int changed;
- int dir = 0;
- do {
- GCObject *w;
- GCObject *next = g->ephemeron; /* get ephemeron list */
- g->ephemeron = NULL; /* tables may return to this list when traversed */
- changed = 0;
- while ((w = next) != NULL) { /* for each ephemeron table */
- Table *h = gco2t(w);
- next = h->gclist; /* list is rebuilt during loop */
- nw2black(h); /* out of the list (for now) */
- if (traverseephemeron(g, h, dir)) { /* marked some value? */
- propagateall(g); /* propagate changes */
- changed = 1; /* will have to revisit all ephemeron tables */
- }
- }
- dir = !dir; /* invert direction next time */
- } while (changed); /* repeat until no more changes */
-}
-
-/* }====================================================== */
-
-
-/*
-** {======================================================
-** Sweep Functions
-** =======================================================
-*/
-
-
-/*
-** clear entries with unmarked keys from all weaktables in list 'l'
-*/
-static void clearbykeys (global_State *g, GCObject *l) {
- for (; l; l = gco2t(l)->gclist) {
- Table *h = gco2t(l);
- Node *limit = gnodelast(h);
- Node *n;
- for (n = gnode(h, 0); n < limit; n++) {
- if (iscleared(g, gckeyN(n))) /* unmarked key? */
- setempty(gval(n)); /* remove entry */
- if (isempty(gval(n))) /* is entry empty? */
- clearkey(n); /* clear its key */
- }
- }
-}
-
-
-/*
-** clear entries with unmarked values from all weaktables in list 'l' up
-** to element 'f'
-*/
-static void clearbyvalues (global_State *g, GCObject *l, GCObject *f) {
- for (; l != f; l = gco2t(l)->gclist) {
- Table *h = gco2t(l);
- Node *n, *limit = gnodelast(h);
- unsigned int i;
- unsigned int asize = h->asize;
- for (i = 0; i < asize; i++) {
- GCObject *o = gcvalarr(h, i);
- if (iscleared(g, o)) /* value was collected? */
- *getArrTag(h, i) = LUA_VEMPTY; /* remove entry */
- }
- for (n = gnode(h, 0); n < limit; n++) {
- if (iscleared(g, gcvalueN(gval(n)))) /* unmarked value? */
- setempty(gval(n)); /* remove entry */
- if (isempty(gval(n))) /* is entry empty? */
- clearkey(n); /* clear its key */
- }
- }
-}
-
-
-static void freeupval (lua_State *L, UpVal *uv) {
- if (upisopen(uv))
- luaF_unlinkupval(uv);
- luaM_free(L, uv);
-}
-
-
-static void freeobj (lua_State *L, GCObject *o) {
- assert_code(l_mem newmem = gettotalbytes(G(L)) - objsize(o));
- switch (o->tt) {
- case LUA_VPROTO:
- luaF_freeproto(L, gco2p(o));
- break;
- case LUA_VUPVAL:
- freeupval(L, gco2upv(o));
- break;
- case LUA_VLCL: {
- LClosure *cl = gco2lcl(o);
- luaM_freemem(L, cl, sizeLclosure(cl->nupvalues));
- break;
- }
- case LUA_VCCL: {
- CClosure *cl = gco2ccl(o);
- luaM_freemem(L, cl, sizeCclosure(cl->nupvalues));
- break;
- }
- case LUA_VTABLE:
- luaH_free(L, gco2t(o));
- break;
- case LUA_VTHREAD:
- luaE_freethread(L, gco2th(o));
- break;
- case LUA_VUSERDATA: {
- Udata *u = gco2u(o);
- luaM_freemem(L, o, sizeudata(u->nuvalue, u->len));
- break;
- }
- case LUA_VSHRSTR: {
- TString *ts = gco2ts(o);
- luaS_remove(L, ts); /* remove it from hash table */
- luaM_freemem(L, ts, sizestrshr(cast_uint(ts->shrlen)));
- break;
- }
- case LUA_VLNGSTR: {
- TString *ts = gco2ts(o);
- if (ts->shrlen == LSTRMEM) /* must free external string? */
- (*ts->falloc)(ts->ud, ts->contents, ts->u.lnglen + 1, 0);
- luaM_freemem(L, ts, luaS_sizelngstr(ts->u.lnglen, ts->shrlen));
- break;
- }
- default: lua_assert(0);
- }
- lua_assert(gettotalbytes(G(L)) == newmem);
-}
-
-
-/*
-** sweep at most 'countin' elements from a list of GCObjects erasing dead
-** objects, where a dead object is one marked with the old (non current)
-** white; change all non-dead objects back to white (and new), preparing
-** for next collection cycle. Return where to continue the traversal or
-** NULL if list is finished.
-*/
-static GCObject **sweeplist (lua_State *L, GCObject **p, l_mem countin) {
- global_State *g = G(L);
- int ow = otherwhite(g);
- int white = luaC_white(g); /* current white */
- while (*p != NULL && countin-- > 0) {
- GCObject *curr = *p;
- int marked = curr->marked;
- if (isdeadm(ow, marked)) { /* is 'curr' dead? */
- *p = curr->next; /* remove 'curr' from list */
- freeobj(L, curr); /* erase 'curr' */
- }
- else { /* change mark to 'white' and age to 'new' */
- curr->marked = cast_byte((marked & ~maskgcbits) | white | G_NEW);
- p = &curr->next; /* go to next element */
- }
- }
- return (*p == NULL) ? NULL : p;
-}
-
-
-/*
-** sweep a list until a live object (or end of list)
-*/
-static GCObject **sweeptolive (lua_State *L, GCObject **p) {
- GCObject **old = p;
- do {
- p = sweeplist(L, p, 1);
- } while (p == old);
- return p;
-}
-
-/* }====================================================== */
-
-
-/*
-** {======================================================
-** Finalization
-** =======================================================
-*/
-
-/*
-** If possible, shrink string table.
-*/
-static void checkSizes (lua_State *L, global_State *g) {
- if (!g->gcemergency) {
- if (g->strt.nuse < g->strt.size / 4) /* string table too big? */
- luaS_resize(L, g->strt.size / 2);
- }
-}
-
-
-/*
-** Get the next udata to be finalized from the 'tobefnz' list, and
-** link it back into the 'allgc' list.
-*/
-static GCObject *udata2finalize (global_State *g) {
- GCObject *o = g->tobefnz; /* get first element */
- lua_assert(tofinalize(o));
- g->tobefnz = o->next; /* remove it from 'tobefnz' list */
- o->next = g->allgc; /* return it to 'allgc' list */
- g->allgc = o;
- resetbit(o->marked, FINALIZEDBIT); /* object is "normal" again */
- if (issweepphase(g))
- makewhite(g, o); /* "sweep" object */
- else if (getage(o) == G_OLD1)
- g->firstold1 = o; /* it is the first OLD1 object in the list */
- return o;
-}
-
-
-static void dothecall (lua_State *L, void *ud) {
- UNUSED(ud);
- luaD_callnoyield(L, L->top.p - 2, 0);
-}
-
-
-static void GCTM (lua_State *L) {
- global_State *g = G(L);
- const TValue *tm;
- TValue v;
- lua_assert(!g->gcemergency);
- setgcovalue(L, &v, udata2finalize(g));
- tm = luaT_gettmbyobj(L, &v, TM_GC);
- if (!notm(tm)) { /* is there a finalizer? */
- TStatus status;
- lu_byte oldah = L->allowhook;
- lu_byte oldgcstp = g->gcstp;
- g->gcstp |= GCSTPGC; /* avoid GC steps */
- L->allowhook = 0; /* stop debug hooks during GC metamethod */
- setobj2s(L, L->top.p++, tm); /* push finalizer... */
- setobj2s(L, L->top.p++, &v); /* ... and its argument */
- L->ci->callstatus |= CIST_FIN; /* will run a finalizer */
- status = luaD_pcall(L, dothecall, NULL, savestack(L, L->top.p - 2), 0);
- L->ci->callstatus &= ~CIST_FIN; /* not running a finalizer anymore */
- L->allowhook = oldah; /* restore hooks */
- g->gcstp = oldgcstp; /* restore state */
- if (l_unlikely(status != LUA_OK)) { /* error while running __gc? */
- luaE_warnerror(L, "__gc");
- L->top.p--; /* pops error object */
- }
- }
-}
-
-
-/*
-** call all pending finalizers
-*/
-static void callallpendingfinalizers (lua_State *L) {
- global_State *g = G(L);
- while (g->tobefnz)
- GCTM(L);
-}
-
-
-/*
-** find last 'next' field in list 'p' list (to add elements in its end)
-*/
-static GCObject **findlast (GCObject **p) {
- while (*p != NULL)
- p = &(*p)->next;
- return p;
-}
-
-
-/*
-** Move all unreachable objects (or 'all' objects) that need
-** finalization from list 'finobj' to list 'tobefnz' (to be finalized).
-** (Note that objects after 'finobjold1' cannot be white, so they
-** don't need to be traversed. In incremental mode, 'finobjold1' is NULL,
-** so the whole list is traversed.)
-*/
-static void separatetobefnz (global_State *g, int all) {
- GCObject *curr;
- GCObject **p = &g->finobj;
- GCObject **lastnext = findlast(&g->tobefnz);
- while ((curr = *p) != g->finobjold1) { /* traverse all finalizable objects */
- lua_assert(tofinalize(curr));
- if (!(iswhite(curr) || all)) /* not being collected? */
- p = &curr->next; /* don't bother with it */
- else {
- if (curr == g->finobjsur) /* removing 'finobjsur'? */
- g->finobjsur = curr->next; /* correct it */
- *p = curr->next; /* remove 'curr' from 'finobj' list */
- curr->next = *lastnext; /* link at the end of 'tobefnz' list */
- *lastnext = curr;
- lastnext = &curr->next;
- }
- }
-}
-
-
-/*
-** If pointer 'p' points to 'o', move it to the next element.
-*/
-static void checkpointer (GCObject **p, GCObject *o) {
- if (o == *p)
- *p = o->next;
-}
-
-
-/*
-** Correct pointers to objects inside 'allgc' list when
-** object 'o' is being removed from the list.
-*/
-static void correctpointers (global_State *g, GCObject *o) {
- checkpointer(&g->survival, o);
- checkpointer(&g->old1, o);
- checkpointer(&g->reallyold, o);
- checkpointer(&g->firstold1, o);
-}
-
-
-/*
-** if object 'o' has a finalizer, remove it from 'allgc' list (must
-** search the list to find it) and link it in 'finobj' list.
-*/
-void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt) {
- global_State *g = G(L);
- if (tofinalize(o) || /* obj. is already marked... */
- gfasttm(g, mt, TM_GC) == NULL || /* or has no finalizer... */
- (g->gcstp & GCSTPCLS)) /* or closing state? */
- return; /* nothing to be done */
- else { /* move 'o' to 'finobj' list */
- GCObject **p;
- if (issweepphase(g)) {
- makewhite(g, o); /* "sweep" object 'o' */
- if (g->sweepgc == &o->next) /* should not remove 'sweepgc' object */
- g->sweepgc = sweeptolive(L, g->sweepgc); /* change 'sweepgc' */
- }
- else
- correctpointers(g, o);
- /* search for pointer pointing to 'o' */
- for (p = &g->allgc; *p != o; p = &(*p)->next) { /* empty */ }
- *p = o->next; /* remove 'o' from 'allgc' list */
- o->next = g->finobj; /* link it in 'finobj' list */
- g->finobj = o;
- l_setbit(o->marked, FINALIZEDBIT); /* mark it as such */
- }
-}
-
-/* }====================================================== */
-
-
-/*
-** {======================================================
-** Generational Collector
-** =======================================================
-*/
-
-/*
-** Fields 'GCmarked' and 'GCmajorminor' are used to control the pace and
-** the mode of the collector. They play several roles, depending on the
-** mode of the collector:
-** * KGC_INC:
-** GCmarked: number of marked bytes during a cycle.
-** GCmajorminor: not used.
-** * KGC_GENMINOR
-** GCmarked: number of bytes that became old since last major collection.
-** GCmajorminor: number of bytes marked in last major collection.
-** * KGC_GENMAJOR
-** GCmarked: number of bytes that became old since last major collection.
-** GCmajorminor: number of bytes marked in last major collection.
-*/
-
-
-/*
-** Set the "time" to wait before starting a new incremental cycle;
-** cycle will start when number of bytes in use hits the threshold of
-** approximately (marked * pause / 100).
-*/
-static void setpause (global_State *g) {
- l_mem threshold = applygcparam(g, PAUSE, g->GCmarked);
- l_mem debt = threshold - gettotalbytes(g);
- if (debt < 0) debt = 0;
- luaE_setdebt(g, debt);
-}
-
-
-/*
-** Sweep a list of objects to enter generational mode. Deletes dead
-** objects and turns the non dead to old. All non-dead threads---which
-** are now old---must be in a gray list. Everything else is not in a
-** gray list. Open upvalues are also kept gray.
-*/
-static void sweep2old (lua_State *L, GCObject **p) {
- GCObject *curr;
- global_State *g = G(L);
- while ((curr = *p) != NULL) {
- if (iswhite(curr)) { /* is 'curr' dead? */
- lua_assert(isdead(g, curr));
- *p = curr->next; /* remove 'curr' from list */
- freeobj(L, curr); /* erase 'curr' */
- }
- else { /* all surviving objects become old */
- setage(curr, G_OLD);
- if (curr->tt == LUA_VTHREAD) { /* threads must be watched */
- lua_State *th = gco2th(curr);
- linkgclist(th, g->grayagain); /* insert into 'grayagain' list */
- }
- else if (curr->tt == LUA_VUPVAL && upisopen(gco2upv(curr)))
- set2gray(curr); /* open upvalues are always gray */
- else /* everything else is black */
- nw2black(curr);
- p = &curr->next; /* go to next element */
- }
- }
-}
-
-
-/*
-** Sweep for generational mode. Delete dead objects. (Because the
-** collection is not incremental, there are no "new white" objects
-** during the sweep. So, any white object must be dead.) For
-** non-dead objects, advance their ages and clear the color of
-** new objects. (Old objects keep their colors.)
-** The ages of G_TOUCHED1 and G_TOUCHED2 objects cannot be advanced
-** here, because these old-generation objects are usually not swept
-** here. They will all be advanced in 'correctgraylist'. That function
-** will also remove objects turned white here from any gray list.
-*/
-static GCObject **sweepgen (lua_State *L, global_State *g, GCObject **p,
- GCObject *limit, GCObject **pfirstold1,
- l_mem *paddedold) {
- static const lu_byte nextage[] = {
- G_SURVIVAL, /* from G_NEW */
- G_OLD1, /* from G_SURVIVAL */
- G_OLD1, /* from G_OLD0 */
- G_OLD, /* from G_OLD1 */
- G_OLD, /* from G_OLD (do not change) */
- G_TOUCHED1, /* from G_TOUCHED1 (do not change) */
- G_TOUCHED2 /* from G_TOUCHED2 (do not change) */
- };
- l_mem addedold = 0;
- int white = luaC_white(g);
- GCObject *curr;
- while ((curr = *p) != limit) {
- if (iswhite(curr)) { /* is 'curr' dead? */
- lua_assert(!isold(curr) && isdead(g, curr));
- *p = curr->next; /* remove 'curr' from list */
- freeobj(L, curr); /* erase 'curr' */
- }
- else { /* correct mark and age */
- int age = getage(curr);
- if (age == G_NEW) { /* new objects go back to white */
- int marked = curr->marked & ~maskgcbits; /* erase GC bits */
- curr->marked = cast_byte(marked | G_SURVIVAL | white);
- }
- else { /* all other objects will be old, and so keep their color */
- lua_assert(age != G_OLD1); /* advanced in 'markold' */
- setage(curr, nextage[age]);
- if (getage(curr) == G_OLD1) {
- addedold += objsize(curr); /* bytes becoming old */
- if (*pfirstold1 == NULL)
- *pfirstold1 = curr; /* first OLD1 object in the list */
- }
- }
- p = &curr->next; /* go to next element */
- }
- }
- *paddedold += addedold;
- return p;
-}
-
-
-/*
-** Correct a list of gray objects. Return a pointer to the last element
-** left on the list, so that we can link another list to the end of
-** this one.
-** Because this correction is done after sweeping, young objects might
-** be turned white and still be in the list. They are only removed.
-** 'TOUCHED1' objects are advanced to 'TOUCHED2' and remain on the list;
-** Non-white threads also remain on the list. 'TOUCHED2' objects and
-** anything else become regular old, are marked black, and are removed
-** from the list.
-*/
-static GCObject **correctgraylist (GCObject **p) {
- GCObject *curr;
- while ((curr = *p) != NULL) {
- GCObject **next = getgclist(curr);
- if (iswhite(curr))
- goto remove; /* remove all white objects */
- else if (getage(curr) == G_TOUCHED1) { /* touched in this cycle? */
- lua_assert(isgray(curr));
- nw2black(curr); /* make it black, for next barrier */
- setage(curr, G_TOUCHED2);
- goto remain; /* keep it in the list and go to next element */
- }
- else if (curr->tt == LUA_VTHREAD) {
- lua_assert(isgray(curr));
- goto remain; /* keep non-white threads on the list */
- }
- else { /* everything else is removed */
- lua_assert(isold(curr)); /* young objects should be white here */
- if (getage(curr) == G_TOUCHED2) /* advance from TOUCHED2... */
- setage(curr, G_OLD); /* ... to OLD */
- nw2black(curr); /* make object black (to be removed) */
- goto remove;
- }
- remove: *p = *next; continue;
- remain: p = next; continue;
- }
- return p;
-}
-
-
-/*
-** Correct all gray lists, coalescing them into 'grayagain'.
-*/
-static void correctgraylists (global_State *g) {
- GCObject **list = correctgraylist(&g->grayagain);
- *list = g->weak; g->weak = NULL;
- list = correctgraylist(list);
- *list = g->allweak; g->allweak = NULL;
- list = correctgraylist(list);
- *list = g->ephemeron; g->ephemeron = NULL;
- correctgraylist(list);
-}
-
-
-/*
-** Mark black 'OLD1' objects when starting a new young collection.
-** Gray objects are already in some gray list, and so will be visited in
-** the atomic step.
-*/
-static void markold (global_State *g, GCObject *from, GCObject *to) {
- GCObject *p;
- for (p = from; p != to; p = p->next) {
- if (getage(p) == G_OLD1) {
- lua_assert(!iswhite(p));
- setage(p, G_OLD); /* now they are old */
- if (isblack(p))
- reallymarkobject(g, p);
- }
- }
-}
-
-
-/*
-** Finish a young-generation collection.
-*/
-static void finishgencycle (lua_State *L, global_State *g) {
- correctgraylists(g);
- checkSizes(L, g);
- g->gcstate = GCSpropagate; /* skip restart */
- if (g->tobefnz != NULL && !g->gcemergency && luaD_checkminstack(L))
- callallpendingfinalizers(L);
-}
-
-
-/*
-** Shifts from a minor collection to major collections. It starts in
-** the "sweep all" state to clear all objects, which are mostly black
-** in generational mode.
-*/
-static void minor2inc (lua_State *L, global_State *g, lu_byte kind) {
- g->GCmajorminor = g->GCmarked; /* number of live bytes */
- g->gckind = kind;
- g->reallyold = g->old1 = g->survival = NULL;
- g->finobjrold = g->finobjold1 = g->finobjsur = NULL;
- entersweep(L); /* continue as an incremental cycle */
- /* set a debt equal to the step size */
- luaE_setdebt(g, applygcparam(g, STEPSIZE, 100));
-}
-
-
-/*
-** Decide whether to shift to major mode. It shifts if the accumulated
-** number of added old bytes (counted in 'GCmarked') is larger than
-** 'minormajor'% of the number of lived bytes after the last major
-** collection. (This number is kept in 'GCmajorminor'.)
-*/
-static int checkminormajor (global_State *g) {
- l_mem limit = applygcparam(g, MINORMAJOR, g->GCmajorminor);
- if (limit == 0)
- return 0; /* special case: 'minormajor' 0 stops major collections */
- return (g->GCmarked >= limit);
-}
-
-/*
-** Does a young collection. First, mark 'OLD1' objects. Then does the
-** atomic step. Then, check whether to continue in minor mode. If so,
-** sweep all lists and advance pointers. Finally, finish the collection.
-*/
-static void youngcollection (lua_State *L, global_State *g) {
- l_mem addedold1 = 0;
- l_mem marked = g->GCmarked; /* preserve 'g->GCmarked' */
- GCObject **psurvival; /* to point to first non-dead survival object */
- GCObject *dummy; /* dummy out parameter to 'sweepgen' */
- lua_assert(g->gcstate == GCSpropagate);
- if (g->firstold1) { /* are there regular OLD1 objects? */
- markold(g, g->firstold1, g->reallyold); /* mark them */
- g->firstold1 = NULL; /* no more OLD1 objects (for now) */
- }
- markold(g, g->finobj, g->finobjrold);
- markold(g, g->tobefnz, NULL);
-
- atomic(L); /* will lose 'g->marked' */
-
- /* sweep nursery and get a pointer to its last live element */
- g->gcstate = GCSswpallgc;
- psurvival = sweepgen(L, g, &g->allgc, g->survival, &g->firstold1, &addedold1);
- /* sweep 'survival' */
- sweepgen(L, g, psurvival, g->old1, &g->firstold1, &addedold1);
- g->reallyold = g->old1;
- g->old1 = *psurvival; /* 'survival' survivals are old now */
- g->survival = g->allgc; /* all news are survivals */
-
- /* repeat for 'finobj' lists */
- dummy = NULL; /* no 'firstold1' optimization for 'finobj' lists */
- psurvival = sweepgen(L, g, &g->finobj, g->finobjsur, &dummy, &addedold1);
- /* sweep 'survival' */
- sweepgen(L, g, psurvival, g->finobjold1, &dummy, &addedold1);
- g->finobjrold = g->finobjold1;
- g->finobjold1 = *psurvival; /* 'survival' survivals are old now */
- g->finobjsur = g->finobj; /* all news are survivals */
-
- sweepgen(L, g, &g->tobefnz, NULL, &dummy, &addedold1);
-
- /* keep total number of added old1 bytes */
- g->GCmarked = marked + addedold1;
-
- /* decide whether to shift to major mode */
- if (checkminormajor(g)) {
- minor2inc(L, g, KGC_GENMAJOR); /* go to major mode */
- g->GCmarked = 0; /* avoid pause in first major cycle (see 'setpause') */
- }
- else
- finishgencycle(L, g); /* still in minor mode; finish it */
-}
-
-
-/*
-** Clears all gray lists, sweeps objects, and prepare sublists to enter
-** generational mode. The sweeps remove dead objects and turn all
-** surviving objects to old. Threads go back to 'grayagain'; everything
-** else is turned black (not in any gray list).
-*/
-static void atomic2gen (lua_State *L, global_State *g) {
- cleargraylists(g);
- /* sweep all elements making them old */
- g->gcstate = GCSswpallgc;
- sweep2old(L, &g->allgc);
- /* everything alive now is old */
- g->reallyold = g->old1 = g->survival = g->allgc;
- g->firstold1 = NULL; /* there are no OLD1 objects anywhere */
-
- /* repeat for 'finobj' lists */
- sweep2old(L, &g->finobj);
- g->finobjrold = g->finobjold1 = g->finobjsur = g->finobj;
-
- sweep2old(L, &g->tobefnz);
-
- g->gckind = KGC_GENMINOR;
- g->GCmajorminor = g->GCmarked; /* "base" for number of bytes */
- g->GCmarked = 0; /* to count the number of added old1 bytes */
- finishgencycle(L, g);
-}
-
-
-/*
-** Set debt for the next minor collection, which will happen when
-** total number of bytes grows 'genminormul'% in relation to
-** the base, GCmajorminor, which is the number of bytes being used
-** after the last major collection.
-*/
-static void setminordebt (global_State *g) {
- luaE_setdebt(g, applygcparam(g, MINORMUL, g->GCmajorminor));
-}
-
-
-/*
-** Enter generational mode. Must go until the end of an atomic cycle
-** to ensure that all objects are correctly marked and weak tables
-** are cleared. Then, turn all objects into old and finishes the
-** collection.
-*/
-static void entergen (lua_State *L, global_State *g) {
- luaC_runtilstate(L, GCSpause, 1); /* prepare to start a new cycle */
- luaC_runtilstate(L, GCSpropagate, 1); /* start new cycle */
- atomic(L); /* propagates all and then do the atomic stuff */
- atomic2gen(L, g);
- setminordebt(g); /* set debt assuming next cycle will be minor */
-}
-
-
-/*
-** Change collector mode to 'newmode'.
-*/
-void luaC_changemode (lua_State *L, int newmode) {
- global_State *g = G(L);
- if (g->gckind == KGC_GENMAJOR) /* doing major collections? */
- g->gckind = KGC_INC; /* already incremental but in name */
- if (newmode != g->gckind) { /* does it need to change? */
- if (newmode == KGC_INC) /* entering incremental mode? */
- minor2inc(L, g, KGC_INC); /* entering incremental mode */
- else {
- lua_assert(newmode == KGC_GENMINOR);
- entergen(L, g);
- }
- }
-}
-
-
-/*
-** Does a full collection in generational mode.
-*/
-static void fullgen (lua_State *L, global_State *g) {
- minor2inc(L, g, KGC_INC);
- entergen(L, g);
-}
-
-
-/*
-** After an atomic incremental step from a major collection,
-** check whether collector could return to minor collections.
-** It checks whether the number of bytes 'tobecollected'
-** is greater than 'majorminor'% of the number of bytes added
-** since the last collection ('addedbytes').
-*/
-static int checkmajorminor (lua_State *L, global_State *g) {
- if (g->gckind == KGC_GENMAJOR) { /* generational mode? */
- l_mem numbytes = gettotalbytes(g);
- l_mem addedbytes = numbytes - g->GCmajorminor;
- l_mem limit = applygcparam(g, MAJORMINOR, addedbytes);
- l_mem tobecollected = numbytes - g->GCmarked;
- if (tobecollected > limit) {
- atomic2gen(L, g); /* return to generational mode */
- setminordebt(g);
- return 1; /* exit incremental collection */
- }
- }
- g->GCmajorminor = g->GCmarked; /* prepare for next collection */
- return 0; /* stay doing incremental collections */
-}
-
-/* }====================================================== */
-
-
-/*
-** {======================================================
-** GC control
-** =======================================================
-*/
-
-
-/*
-** Enter first sweep phase.
-** The call to 'sweeptolive' makes the pointer point to an object
-** inside the list (instead of to the header), so that the real sweep do
-** not need to skip objects created between "now" and the start of the
-** real sweep.
-*/
-static void entersweep (lua_State *L) {
- global_State *g = G(L);
- g->gcstate = GCSswpallgc;
- lua_assert(g->sweepgc == NULL);
- g->sweepgc = sweeptolive(L, &g->allgc);
-}
-
-
-/*
-** Delete all objects in list 'p' until (but not including) object
-** 'limit'.
-*/
-static void deletelist (lua_State *L, GCObject *p, GCObject *limit) {
- while (p != limit) {
- GCObject *next = p->next;
- freeobj(L, p);
- p = next;
- }
-}
-
-
-/*
-** Call all finalizers of the objects in the given Lua state, and
-** then free all objects, except for the main thread.
-*/
-void luaC_freeallobjects (lua_State *L) {
- global_State *g = G(L);
- g->gcstp = GCSTPCLS; /* no extra finalizers after here */
- luaC_changemode(L, KGC_INC);
- separatetobefnz(g, 1); /* separate all objects with finalizers */
- lua_assert(g->finobj == NULL);
- callallpendingfinalizers(L);
- deletelist(L, g->allgc, obj2gco(mainthread(g)));
- lua_assert(g->finobj == NULL); /* no new finalizers */
- deletelist(L, g->fixedgc, NULL); /* collect fixed objects */
- lua_assert(g->strt.nuse == 0);
-}
-
-
-static void atomic (lua_State *L) {
- global_State *g = G(L);
- GCObject *origweak, *origall;
- GCObject *grayagain = g->grayagain; /* save original list */
- g->grayagain = NULL;
- lua_assert(g->ephemeron == NULL && g->weak == NULL);
- lua_assert(!iswhite(mainthread(g)));
- g->gcstate = GCSatomic;
- markobject(g, L); /* mark running thread */
- /* registry and global metatables may be changed by API */
- markvalue(g, &g->l_registry);
- markmt(g); /* mark global metatables */
- propagateall(g); /* empties 'gray' list */
- /* remark occasional upvalues of (maybe) dead threads */
- remarkupvals(g);
- propagateall(g); /* propagate changes */
- g->gray = grayagain;
- propagateall(g); /* traverse 'grayagain' list */
- convergeephemerons(g);
- /* at this point, all strongly accessible objects are marked. */
- /* Clear values from weak tables, before checking finalizers */
- clearbyvalues(g, g->weak, NULL);
- clearbyvalues(g, g->allweak, NULL);
- origweak = g->weak; origall = g->allweak;
- separatetobefnz(g, 0); /* separate objects to be finalized */
- markbeingfnz(g); /* mark objects that will be finalized */
- propagateall(g); /* remark, to propagate 'resurrection' */
- convergeephemerons(g);
- /* at this point, all resurrected objects are marked. */
- /* remove dead objects from weak tables */
- clearbykeys(g, g->ephemeron); /* clear keys from all ephemeron */
- clearbykeys(g, g->allweak); /* clear keys from all 'allweak' */
- /* clear values from resurrected weak tables */
- clearbyvalues(g, g->weak, origweak);
- clearbyvalues(g, g->allweak, origall);
- luaS_clearcache(g);
- g->currentwhite = cast_byte(otherwhite(g)); /* flip current white */
- lua_assert(g->gray == NULL);
-}
-
-
-/*
-** Do a sweep step. The normal case (not fast) sweeps at most GCSWEEPMAX
-** elements. The fast case sweeps the whole list.
-*/
-static void sweepstep (lua_State *L, global_State *g,
- lu_byte nextstate, GCObject **nextlist, int fast) {
- if (g->sweepgc)
- g->sweepgc = sweeplist(L, g->sweepgc, fast ? MAX_LMEM : GCSWEEPMAX);
- else { /* enter next state */
- g->gcstate = nextstate;
- g->sweepgc = nextlist;
- }
-}
-
-
-/*
-** Performs one incremental "step" in an incremental garbage collection.
-** For indivisible work, a step goes to the next state. When marking
-** (propagating), a step traverses one object. When sweeping, a step
-** sweeps GCSWEEPMAX objects, to avoid a big overhead for sweeping
-** objects one by one. (Sweeping is inexpensive, no matter the
-** object.) When 'fast' is true, 'singlestep' tries to finish a state
-** "as fast as possible". In particular, it skips the propagation
-** phase and leaves all objects to be traversed by the atomic phase:
-** That avoids traversing twice some objects, such as threads and
-** weak tables.
-*/
-
-#define step2pause -3 /* finished collection; entered pause state */
-#define atomicstep -2 /* atomic step */
-#define step2minor -1 /* moved to minor collections */
-
-
-static l_mem singlestep (lua_State *L, int fast) {
- global_State *g = G(L);
- l_mem stepresult;
- lua_assert(!g->gcstopem); /* collector is not reentrant */
- g->gcstopem = 1; /* no emergency collections while collecting */
- switch (g->gcstate) {
- case GCSpause: {
- restartcollection(g);
- g->gcstate = GCSpropagate;
- stepresult = 1;
- break;
- }
- case GCSpropagate: {
- if (fast || g->gray == NULL) {
- g->gcstate = GCSenteratomic; /* finish propagate phase */
- stepresult = 1;
- }
- else
- stepresult = propagatemark(g); /* traverse one gray object */
- break;
- }
- case GCSenteratomic: {
- atomic(L);
- if (checkmajorminor(L, g))
- stepresult = step2minor;
- else {
- entersweep(L);
- stepresult = atomicstep;
- }
- break;
- }
- case GCSswpallgc: { /* sweep "regular" objects */
- sweepstep(L, g, GCSswpfinobj, &g->finobj, fast);
- stepresult = GCSWEEPMAX;
- break;
- }
- case GCSswpfinobj: { /* sweep objects with finalizers */
- sweepstep(L, g, GCSswptobefnz, &g->tobefnz, fast);
- stepresult = GCSWEEPMAX;
- break;
- }
- case GCSswptobefnz: { /* sweep objects to be finalized */
- sweepstep(L, g, GCSswpend, NULL, fast);
- stepresult = GCSWEEPMAX;
- break;
- }
- case GCSswpend: { /* finish sweeps */
- checkSizes(L, g);
- g->gcstate = GCScallfin;
- stepresult = GCSWEEPMAX;
- break;
- }
- case GCScallfin: { /* call finalizers */
- if (g->tobefnz && !g->gcemergency && luaD_checkminstack(L)) {
- g->gcstopem = 0; /* ok collections during finalizers */
- GCTM(L); /* call one finalizer */
- stepresult = CWUFIN;
- }
- else { /* no more finalizers or emergency mode or not enough stack
- to run finalizers */
- g->gcstate = GCSpause; /* finish collection */
- stepresult = step2pause;
- }
- break;
- }
- default: lua_assert(0); return 0;
- }
- g->gcstopem = 0;
- return stepresult;
-}
-
-
-/*
-** Advances the garbage collector until it reaches the given state.
-** (The option 'fast' is only for testing; in normal code, 'fast'
-** here is always true.)
-*/
-void luaC_runtilstate (lua_State *L, int state, int fast) {
- global_State *g = G(L);
- lua_assert(g->gckind == KGC_INC);
- while (state != g->gcstate)
- singlestep(L, fast);
-}
-
-
-
-/*
-** Performs a basic incremental step. The step size is
-** converted from bytes to "units of work"; then the function loops
-** running single steps until adding that many units of work or
-** finishing a cycle (pause state). Finally, it sets the debt that
-** controls when next step will be performed.
-*/
-static void incstep (lua_State *L, global_State *g) {
- l_mem stepsize = applygcparam(g, STEPSIZE, 100);
- l_mem work2do = applygcparam(g, STEPMUL, stepsize / cast_int(sizeof(void*)));
- l_mem stres;
- int fast = (work2do == 0); /* special case: do a full collection */
- do { /* repeat until enough work */
- stres = singlestep(L, fast); /* perform one single step */
- if (stres == step2minor) /* returned to minor collections? */
- return; /* nothing else to be done here */
- else if (stres == step2pause || (stres == atomicstep && !fast))
- break; /* end of cycle or atomic */
- else
- work2do -= stres;
- } while (fast || work2do > 0);
- if (g->gcstate == GCSpause)
- setpause(g); /* pause until next cycle */
- else
- luaE_setdebt(g, stepsize);
-}
-
-
-#if !defined(luai_tracegc)
-#define luai_tracegc(L,f) ((void)0)
-#endif
-
-/*
-** Performs a basic GC step if collector is running. (If collector was
-** stopped by the user, set a reasonable debt to avoid it being called
-** at every single check.)
-*/
-void luaC_step (lua_State *L) {
- global_State *g = G(L);
- lua_assert(!g->gcemergency);
- if (!gcrunning(g)) { /* not running? */
- if (g->gcstp & GCSTPUSR) /* stopped by the user? */
- luaE_setdebt(g, 20000);
- }
- else {
- luai_tracegc(L, 1); /* for internal debugging */
- switch (g->gckind) {
- case KGC_INC: case KGC_GENMAJOR:
- incstep(L, g);
- break;
- case KGC_GENMINOR:
- youngcollection(L, g);
- setminordebt(g);
- break;
- }
- luai_tracegc(L, 0); /* for internal debugging */
- }
-}
-
-
-/*
-** Perform a full collection in incremental mode.
-** Before running the collection, check 'keepinvariant'; if it is true,
-** there may be some objects marked as black, so the collector has
-** to sweep all objects to turn them back to white (as white has not
-** changed, nothing will be collected).
-*/
-static void fullinc (lua_State *L, global_State *g) {
- if (keepinvariant(g)) /* black objects? */
- entersweep(L); /* sweep everything to turn them back to white */
- /* finish any pending sweep phase to start a new cycle */
- luaC_runtilstate(L, GCSpause, 1);
- luaC_runtilstate(L, GCScallfin, 1); /* run up to finalizers */
- luaC_runtilstate(L, GCSpause, 1); /* finish collection */
- setpause(g);
-}
-
-
-/*
-** Performs a full GC cycle; if 'isemergency', set a flag to avoid
-** some operations which could change the interpreter state in some
-** unexpected ways (running finalizers and shrinking some structures).
-*/
-void luaC_fullgc (lua_State *L, int isemergency) {
- global_State *g = G(L);
- lua_assert(!g->gcemergency);
- g->gcemergency = cast_byte(isemergency); /* set flag */
- switch (g->gckind) {
- case KGC_GENMINOR: fullgen(L, g); break;
- case KGC_INC: fullinc(L, g); break;
- case KGC_GENMAJOR:
- g->gckind = KGC_INC;
- fullinc(L, g);
- g->gckind = KGC_GENMAJOR;
- break;
- }
- g->gcemergency = 0;
-}
-
-/* }====================================================== */
-
-
diff --git a/lgc.h b/lgc.h
deleted file mode 100644
index ee0541793b..0000000000
--- a/lgc.h
+++ /dev/null
@@ -1,268 +0,0 @@
-/*
-** $Id: lgc.h $
-** Garbage Collector
-** See Copyright Notice in lua.h
-*/
-
-#ifndef lgc_h
-#define lgc_h
-
-
-#include
-
-
-#include "lobject.h"
-#include "lstate.h"
-
-/*
-** Collectable objects may have one of three colors: white, which means
-** the object is not marked; gray, which means the object is marked, but
-** its references may be not marked; and black, which means that the
-** object and all its references are marked. The main invariant of the
-** garbage collector, while marking objects, is that a black object can
-** never point to a white one. Moreover, any gray object must be in a
-** "gray list" (gray, grayagain, weak, allweak, ephemeron) so that it
-** can be visited again before finishing the collection cycle. (Open
-** upvalues are an exception to this rule, as they are attached to
-** a corresponding thread.) These lists have no meaning when the
-** invariant is not being enforced (e.g., sweep phase).
-*/
-
-
-/*
-** Possible states of the Garbage Collector
-*/
-#define GCSpropagate 0
-#define GCSenteratomic 1
-#define GCSatomic 2
-#define GCSswpallgc 3
-#define GCSswpfinobj 4
-#define GCSswptobefnz 5
-#define GCSswpend 6
-#define GCScallfin 7
-#define GCSpause 8
-
-
-#define issweepphase(g) \
- (GCSswpallgc <= (g)->gcstate && (g)->gcstate <= GCSswpend)
-
-
-/*
-** macro to tell when main invariant (white objects cannot point to black
-** ones) must be kept. During a collection, the sweep phase may break
-** the invariant, as objects turned white may point to still-black
-** objects. The invariant is restored when sweep ends and all objects
-** are white again.
-*/
-
-#define keepinvariant(g) ((g)->gcstate <= GCSatomic)
-
-
-/*
-** some useful bit tricks
-*/
-#define resetbits(x,m) ((x) &= cast_byte(~(m)))
-#define setbits(x,m) ((x) |= (m))
-#define testbits(x,m) ((x) & (m))
-#define bitmask(b) (1<<(b))
-#define bit2mask(b1,b2) (bitmask(b1) | bitmask(b2))
-#define l_setbit(x,b) setbits(x, bitmask(b))
-#define resetbit(x,b) resetbits(x, bitmask(b))
-#define testbit(x,b) testbits(x, bitmask(b))
-
-
-/*
-** Layout for bit use in 'marked' field. First three bits are
-** used for object "age" in generational mode. Last bit is used
-** by tests.
-*/
-#define WHITE0BIT 3 /* object is white (type 0) */
-#define WHITE1BIT 4 /* object is white (type 1) */
-#define BLACKBIT 5 /* object is black */
-#define FINALIZEDBIT 6 /* object has been marked for finalization */
-
-#define TESTBIT 7
-
-
-
-#define WHITEBITS bit2mask(WHITE0BIT, WHITE1BIT)
-
-
-#define iswhite(x) testbits((x)->marked, WHITEBITS)
-#define isblack(x) testbit((x)->marked, BLACKBIT)
-#define isgray(x) /* neither white nor black */ \
- (!testbits((x)->marked, WHITEBITS | bitmask(BLACKBIT)))
-
-#define tofinalize(x) testbit((x)->marked, FINALIZEDBIT)
-
-#define otherwhite(g) ((g)->currentwhite ^ WHITEBITS)
-#define isdeadm(ow,m) ((m) & (ow))
-#define isdead(g,v) isdeadm(otherwhite(g), (v)->marked)
-
-#define changewhite(x) ((x)->marked ^= WHITEBITS)
-#define nw2black(x) \
- check_exp(!iswhite(x), l_setbit((x)->marked, BLACKBIT))
-
-#define luaC_white(g) cast_byte((g)->currentwhite & WHITEBITS)
-
-
-/* object age in generational mode */
-#define G_NEW 0 /* created in current cycle */
-#define G_SURVIVAL 1 /* created in previous cycle */
-#define G_OLD0 2 /* marked old by frw. barrier in this cycle */
-#define G_OLD1 3 /* first full cycle as old */
-#define G_OLD 4 /* really old object (not to be visited) */
-#define G_TOUCHED1 5 /* old object touched this cycle */
-#define G_TOUCHED2 6 /* old object touched in previous cycle */
-
-#define AGEBITS 7 /* all age bits (111) */
-
-#define getage(o) ((o)->marked & AGEBITS)
-#define setage(o,a) ((o)->marked = cast_byte(((o)->marked & (~AGEBITS)) | a))
-#define isold(o) (getage(o) > G_SURVIVAL)
-
-
-/*
-** In generational mode, objects are created 'new'. After surviving one
-** cycle, they become 'survival'. Both 'new' and 'survival' can point
-** to any other object, as they are traversed at the end of the cycle.
-** We call them both 'young' objects.
-** If a survival object survives another cycle, it becomes 'old1'.
-** 'old1' objects can still point to survival objects (but not to
-** new objects), so they still must be traversed. After another cycle
-** (that, being old, 'old1' objects will "survive" no matter what)
-** finally the 'old1' object becomes really 'old', and then they
-** are no more traversed.
-**
-** To keep its invariants, the generational mode uses the same barriers
-** also used by the incremental mode. If a young object is caught in a
-** forward barrier, it cannot become old immediately, because it can
-** still point to other young objects. Instead, it becomes 'old0',
-** which in the next cycle becomes 'old1'. So, 'old0' objects is
-** old but can point to new and survival objects; 'old1' is old
-** but cannot point to new objects; and 'old' cannot point to any
-** young object.
-**
-** If any old object ('old0', 'old1', 'old') is caught in a back
-** barrier, it becomes 'touched1' and goes into a gray list, to be
-** visited at the end of the cycle. There it evolves to 'touched2',
-** which can point to survivals but not to new objects. In yet another
-** cycle then it becomes 'old' again.
-**
-** The generational mode must also control the colors of objects,
-** because of the barriers. While the mutator is running, young objects
-** are kept white. 'old', 'old1', and 'touched2' objects are kept black,
-** as they cannot point to new objects; exceptions are threads and open
-** upvalues, which age to 'old1' and 'old' but are kept gray. 'old0'
-** objects may be gray or black, as in the incremental mode. 'touched1'
-** objects are kept gray, as they must be visited again at the end of
-** the cycle.
-*/
-
-
-/*
-** {======================================================
-** Default Values for GC parameters
-** =======================================================
-*/
-
-/*
-** Minor collections will shift to major ones after LUAI_MINORMAJOR%
-** bytes become old.
-*/
-#define LUAI_MINORMAJOR 70
-
-/*
-** Major collections will shift to minor ones after a collection
-** collects at least LUAI_MAJORMINOR% of the new bytes.
-*/
-#define LUAI_MAJORMINOR 50
-
-/*
-** A young (minor) collection will run after creating LUAI_GENMINORMUL%
-** new bytes.
-*/
-#define LUAI_GENMINORMUL 20
-
-
-/* incremental */
-
-/* Number of bytes must be LUAI_GCPAUSE% before starting new cycle */
-#define LUAI_GCPAUSE 250
-
-/*
-** Step multiplier: The collector handles LUAI_GCMUL% work units for
-** each new allocated word. (Each "work unit" corresponds roughly to
-** sweeping one object or traversing one slot.)
-*/
-#define LUAI_GCMUL 200
-
-/* How many bytes to allocate before next GC step */
-#define LUAI_GCSTEPSIZE (200 * sizeof(Table))
-
-
-#define setgcparam(g,p,v) (g->gcparams[LUA_GCP##p] = luaO_codeparam(v))
-#define applygcparam(g,p,x) luaO_applyparam(g->gcparams[LUA_GCP##p], x)
-
-/* }====================================================== */
-
-
-/*
-** Control when GC is running:
-*/
-#define GCSTPUSR 1 /* bit true when GC stopped by user */
-#define GCSTPGC 2 /* bit true when GC stopped by itself */
-#define GCSTPCLS 4 /* bit true when closing Lua state */
-#define gcrunning(g) ((g)->gcstp == 0)
-
-
-/*
-** Does one step of collection when debt becomes zero. 'pre'/'pos'
-** allows some adjustments to be done only when needed. macro
-** 'condchangemem' is used only for heavy tests (forcing a full
-** GC cycle on every opportunity)
-*/
-
-#if !defined(HARDMEMTESTS)
-#define condchangemem(L,pre,pos,emg) ((void)0)
-#else
-#define condchangemem(L,pre,pos,emg) \
- { if (gcrunning(G(L))) { pre; luaC_fullgc(L, emg); pos; } }
-#endif
-
-#define luaC_condGC(L,pre,pos) \
- { if (G(L)->GCdebt <= 0) { pre; luaC_step(L); pos;}; \
- condchangemem(L,pre,pos,0); }
-
-/* more often than not, 'pre'/'pos' are empty */
-#define luaC_checkGC(L) luaC_condGC(L,(void)0,(void)0)
-
-
-#define luaC_objbarrier(L,p,o) ( \
- (isblack(p) && iswhite(o)) ? \
- luaC_barrier_(L,obj2gco(p),obj2gco(o)) : cast_void(0))
-
-#define luaC_barrier(L,p,v) ( \
- iscollectable(v) ? luaC_objbarrier(L,p,gcvalue(v)) : cast_void(0))
-
-#define luaC_objbarrierback(L,p,o) ( \
- (isblack(p) && iswhite(o)) ? luaC_barrierback_(L,p) : cast_void(0))
-
-#define luaC_barrierback(L,p,v) ( \
- iscollectable(v) ? luaC_objbarrierback(L, p, gcvalue(v)) : cast_void(0))
-
-LUAI_FUNC void luaC_fix (lua_State *L, GCObject *o);
-LUAI_FUNC void luaC_freeallobjects (lua_State *L);
-LUAI_FUNC void luaC_step (lua_State *L);
-LUAI_FUNC void luaC_runtilstate (lua_State *L, int state, int fast);
-LUAI_FUNC void luaC_fullgc (lua_State *L, int isemergency);
-LUAI_FUNC GCObject *luaC_newobj (lua_State *L, lu_byte tt, size_t sz);
-LUAI_FUNC GCObject *luaC_newobjdt (lua_State *L, lu_byte tt, size_t sz,
- size_t offset);
-LUAI_FUNC void luaC_barrier_ (lua_State *L, GCObject *o, GCObject *v);
-LUAI_FUNC void luaC_barrierback_ (lua_State *L, GCObject *o);
-LUAI_FUNC void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt);
-LUAI_FUNC void luaC_changemode (lua_State *L, int newmode);
-
-
-#endif
diff --git a/linit.c b/linit.c
deleted file mode 100644
index 00d06f7ecb..0000000000
--- a/linit.c
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
-** $Id: linit.c $
-** Initialization of libraries for lua.c and other clients
-** See Copyright Notice in lua.h
-*/
-
-
-#define linit_c
-#define LUA_LIB
-
-
-#include "lprefix.h"
-
-
-#include
-
-#include "lua.h"
-
-#include "lualib.h"
-#include "lauxlib.h"
-#include "llimits.h"
-
-
-/*
-** Standard Libraries. (Must be listed in the same ORDER of their
-** respective constants LUA_K.)
-*/
-static const luaL_Reg stdlibs[] = {
- {LUA_GNAME, luaopen_base},
- {LUA_LOADLIBNAME, luaopen_package},
- {LUA_COLIBNAME, luaopen_coroutine},
- {LUA_DBLIBNAME, luaopen_debug},
- {LUA_IOLIBNAME, luaopen_io},
- {LUA_MATHLIBNAME, luaopen_math},
- {LUA_OSLIBNAME, luaopen_os},
- {LUA_STRLIBNAME, luaopen_string},
- {LUA_TABLIBNAME, luaopen_table},
- {LUA_UTF8LIBNAME, luaopen_utf8},
- {NULL, NULL}
-};
-
-
-/*
-** require and preload selected standard libraries
-*/
-LUALIB_API void luaL_openselectedlibs (lua_State *L, int load, int preload) {
- int mask;
- const luaL_Reg *lib;
- luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_PRELOAD_TABLE);
- for (lib = stdlibs, mask = 1; lib->name != NULL; lib++, mask <<= 1) {
- if (load & mask) { /* selected? */
- luaL_requiref(L, lib->name, lib->func, 1); /* require library */
- lua_pop(L, 1); /* remove result from the stack */
- }
- else if (preload & mask) { /* selected? */
- lua_pushcfunction(L, lib->func);
- lua_setfield(L, -2, lib->name); /* add library to PRELOAD table */
- }
- }
- lua_assert((mask >> 1) == LUA_UTF8LIBK);
- lua_pop(L, 1); /* remove PRELOAD table */
-}
-
diff --git a/ljumptab.h b/ljumptab.h
deleted file mode 100644
index 52fa6d746e..0000000000
--- a/ljumptab.h
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
-** $Id: ljumptab.h $
-** Jump Table for the Lua interpreter
-** See Copyright Notice in lua.h
-*/
-
-
-#undef vmdispatch
-#undef vmcase
-#undef vmbreak
-
-#define vmdispatch(x) goto *disptab[x];
-
-#define vmcase(l) L_##l:
-
-#define vmbreak vmfetch(); vmdispatch(GET_OPCODE(i));
-
-
-static const void *const disptab[NUM_OPCODES] = {
-
-#if 0
-** you can update the following list with this command:
-**
-** sed -n '/^OP_/!d; s/OP_/\&\&L_OP_/ ; s/,.*/,/ ; s/\/.*// ; p' lopcodes.h
-**
-#endif
-
-&&L_OP_MOVE,
-&&L_OP_LOADI,
-&&L_OP_LOADF,
-&&L_OP_LOADK,
-&&L_OP_LOADKX,
-&&L_OP_LOADFALSE,
-&&L_OP_LFALSESKIP,
-&&L_OP_LOADTRUE,
-&&L_OP_LOADNIL,
-&&L_OP_GETUPVAL,
-&&L_OP_SETUPVAL,
-&&L_OP_GETTABUP,
-&&L_OP_GETTABLE,
-&&L_OP_GETI,
-&&L_OP_GETFIELD,
-&&L_OP_SETTABUP,
-&&L_OP_SETTABLE,
-&&L_OP_SETI,
-&&L_OP_SETFIELD,
-&&L_OP_NEWTABLE,
-&&L_OP_SELF,
-&&L_OP_ADDI,
-&&L_OP_ADDK,
-&&L_OP_SUBK,
-&&L_OP_MULK,
-&&L_OP_MODK,
-&&L_OP_POWK,
-&&L_OP_DIVK,
-&&L_OP_IDIVK,
-&&L_OP_BANDK,
-&&L_OP_BORK,
-&&L_OP_BXORK,
-&&L_OP_SHLI,
-&&L_OP_SHRI,
-&&L_OP_ADD,
-&&L_OP_SUB,
-&&L_OP_MUL,
-&&L_OP_MOD,
-&&L_OP_POW,
-&&L_OP_DIV,
-&&L_OP_IDIV,
-&&L_OP_BAND,
-&&L_OP_BOR,
-&&L_OP_BXOR,
-&&L_OP_SHL,
-&&L_OP_SHR,
-&&L_OP_MMBIN,
-&&L_OP_MMBINI,
-&&L_OP_MMBINK,
-&&L_OP_UNM,
-&&L_OP_BNOT,
-&&L_OP_NOT,
-&&L_OP_LEN,
-&&L_OP_CONCAT,
-&&L_OP_CLOSE,
-&&L_OP_TBC,
-&&L_OP_JMP,
-&&L_OP_EQ,
-&&L_OP_LT,
-&&L_OP_LE,
-&&L_OP_EQK,
-&&L_OP_EQI,
-&&L_OP_LTI,
-&&L_OP_LEI,
-&&L_OP_GTI,
-&&L_OP_GEI,
-&&L_OP_TEST,
-&&L_OP_TESTSET,
-&&L_OP_CALL,
-&&L_OP_TAILCALL,
-&&L_OP_RETURN,
-&&L_OP_RETURN0,
-&&L_OP_RETURN1,
-&&L_OP_FORLOOP,
-&&L_OP_FORPREP,
-&&L_OP_TFORPREP,
-&&L_OP_TFORCALL,
-&&L_OP_TFORLOOP,
-&&L_OP_SETLIST,
-&&L_OP_CLOSURE,
-&&L_OP_VARARG,
-&&L_OP_GETVARG,
-&&L_OP_ERRNNIL,
-&&L_OP_VARARGPREP,
-&&L_OP_EXTRAARG
-
-};
diff --git a/llimits.h b/llimits.h
deleted file mode 100644
index 3f0372552a..0000000000
--- a/llimits.h
+++ /dev/null
@@ -1,357 +0,0 @@
-/*
-** $Id: llimits.h $
-** Limits, basic types, and some other 'installation-dependent' definitions
-** See Copyright Notice in lua.h
-*/
-
-#ifndef llimits_h
-#define llimits_h
-
-
-#include
-#include
-
-
-#include "lua.h"
-
-
-#define l_numbits(t) cast_int(sizeof(t) * CHAR_BIT)
-
-/*
-** 'l_mem' is a signed integer big enough to count the total memory
-** used by Lua. (It is signed due to the use of debt in several
-** computations.) 'lu_mem' is a corresponding unsigned type. Usually,
-** 'ptrdiff_t' should work, but we use 'long' for 16-bit machines.
-*/
-#if defined(LUAI_MEM) /* { external definitions? */
-typedef LUAI_MEM l_mem;
-typedef LUAI_UMEM lu_mem;
-#elif LUAI_IS32INT /* }{ */
-typedef ptrdiff_t l_mem;
-typedef size_t lu_mem;
-#else /* 16-bit ints */ /* }{ */
-typedef long l_mem;
-typedef unsigned long lu_mem;
-#endif /* } */
-
-#define MAX_LMEM \
- cast(l_mem, (cast(lu_mem, 1) << (l_numbits(l_mem) - 1)) - 1)
-
-
-/* chars used as small naturals (so that 'char' is reserved for characters) */
-typedef unsigned char lu_byte;
-typedef signed char ls_byte;
-
-
-/* Type for thread status/error codes */
-typedef lu_byte TStatus;
-
-/* The C API still uses 'int' for status/error codes */
-#define APIstatus(st) cast_int(st)
-
-/* maximum value for size_t */
-#define MAX_SIZET ((size_t)(~(size_t)0))
-
-/*
-** Maximum size for strings and userdata visible for Lua; should be
-** representable as a lua_Integer and as a size_t.
-*/
-#define MAX_SIZE (sizeof(size_t) < sizeof(lua_Integer) ? MAX_SIZET \
- : cast_sizet(LUA_MAXINTEGER))
-
-/*
-** test whether an unsigned value is a power of 2 (or zero)
-*/
-#define ispow2(x) (((x) & ((x) - 1)) == 0)
-
-
-/* number of chars of a literal string without the ending \0 */
-#define LL(x) (sizeof(x)/sizeof(char) - 1)
-
-
-/*
-** conversion of pointer to unsigned integer: this is for hashing only;
-** there is no problem if the integer cannot hold the whole pointer
-** value. (In strict ISO C this may cause undefined behavior, but no
-** actual machine seems to bother.)
-*/
-#if !defined(LUA_USE_C89) && defined(__STDC_VERSION__) && \
- __STDC_VERSION__ >= 199901L
-#include
-#if defined(UINTPTR_MAX) /* even in C99 this type is optional */
-#define L_P2I uintptr_t
-#else /* no 'intptr'? */
-#define L_P2I uintmax_t /* use the largest available integer */
-#endif
-#else /* C89 option */
-#define L_P2I size_t
-#endif
-
-#define point2uint(p) cast_uint((L_P2I)(p) & UINT_MAX)
-
-
-
-/* types of 'usual argument conversions' for lua_Number and lua_Integer */
-typedef LUAI_UACNUMBER l_uacNumber;
-typedef LUAI_UACINT l_uacInt;
-
-
-/*
-** Internal assertions for in-house debugging
-*/
-#if defined LUAI_ASSERT
-#undef NDEBUG
-#include
-#define lua_assert(c) assert(c)
-#define assert_code(c) c
-#endif
-
-#if defined(lua_assert)
-#else
-#define lua_assert(c) ((void)0)
-#define assert_code(c) ((void)0)
-#endif
-
-#define check_exp(c,e) (lua_assert(c), (e))
-/* to avoid problems with conditions too long */
-#define lua_longassert(c) assert_code((c) ? (void)0 : lua_assert(0))
-
-
-/* macro to avoid warnings about unused variables */
-#if !defined(UNUSED)
-#define UNUSED(x) ((void)(x))
-#endif
-
-
-/* type casts (a macro highlights casts in the code) */
-#define cast(t, exp) ((t)(exp))
-
-#define cast_void(i) cast(void, (i))
-#define cast_voidp(i) cast(void *, (i))
-#define cast_num(i) cast(lua_Number, (i))
-#define cast_int(i) cast(int, (i))
-#define cast_short(i) cast(short, (i))
-#define cast_uint(i) cast(unsigned int, (i))
-#define cast_byte(i) cast(lu_byte, (i))
-#define cast_uchar(i) cast(unsigned char, (i))
-#define cast_char(i) cast(char, (i))
-#define cast_charp(i) cast(char *, (i))
-#define cast_sizet(i) cast(size_t, (i))
-#define cast_Integer(i) cast(lua_Integer, (i))
-#define cast_Inst(i) cast(Instruction, (i))
-
-
-/* cast a signed lua_Integer to lua_Unsigned */
-#if !defined(l_castS2U)
-#define l_castS2U(i) ((lua_Unsigned)(i))
-#endif
-
-/*
-** cast a lua_Unsigned to a signed lua_Integer; this cast is
-** not strict ISO C, but two-complement architectures should
-** work fine.
-*/
-#if !defined(l_castU2S)
-#define l_castU2S(i) ((lua_Integer)(i))
-#endif
-
-/*
-** cast a size_t to lua_Integer: These casts are always valid for
-** sizes of Lua objects (see MAX_SIZE)
-*/
-#define cast_st2S(sz) ((lua_Integer)(sz))
-
-/* Cast a ptrdiff_t to size_t, when it is known that the minuend
-** comes from the subtrahend (the base)
-*/
-#define ct_diff2sz(df) ((size_t)(df))
-
-/* ptrdiff_t to lua_Integer */
-#define ct_diff2S(df) cast_st2S(ct_diff2sz(df))
-
-/*
-** Special type equivalent to '(void*)' for functions (to suppress some
-** warnings when converting function pointers)
-*/
-typedef void (*voidf)(void);
-
-/*
-** Macro to convert pointer-to-void* to pointer-to-function. This cast
-** is undefined according to ISO C, but POSIX assumes that it works.
-** (The '__extension__' in gnu compilers is only to avoid warnings.)
-*/
-#if defined(__GNUC__)
-#define cast_func(p) (__extension__ (voidf)(p))
-#else
-#define cast_func(p) ((voidf)(p))
-#endif
-
-
-
-/*
-** non-return type
-*/
-#if !defined(l_noret)
-
-#if defined(__GNUC__)
-#define l_noret void __attribute__((noreturn))
-#elif defined(_MSC_VER) && _MSC_VER >= 1200
-#define l_noret void __declspec(noreturn)
-#else
-#define l_noret void
-#endif
-
-#endif
-
-
-/*
-** Inline functions
-*/
-#if !defined(LUA_USE_C89)
-#define l_inline inline
-#elif defined(__GNUC__)
-#define l_inline __inline__
-#else
-#define l_inline /* empty */
-#endif
-
-#define l_sinline static l_inline
-
-
-/*
-** An unsigned with (at least) 4 bytes
-*/
-#if LUAI_IS32INT
-typedef unsigned int l_uint32;
-#else
-typedef unsigned long l_uint32;
-#endif
-
-
-/*
-** The luai_num* macros define the primitive operations over numbers.
-*/
-
-/* floor division (defined as 'floor(a/b)') */
-#if !defined(luai_numidiv)
-#define luai_numidiv(L,a,b) l_floor(luai_numdiv(L,a,b))
-#endif
-
-/* float division */
-#if !defined(luai_numdiv)
-#define luai_numdiv(L,a,b) ((void)L, (a)/(b))
-#endif
-
-/*
-** modulo: defined as 'a - floor(a/b)*b'; the direct computation
-** using this definition has several problems with rounding errors,
-** so it is better to use 'fmod'. 'fmod' gives the result of
-** 'a - trunc(a/b)*b', and therefore must be corrected when
-** 'trunc(a/b) ~= floor(a/b)'. That happens when the division has a
-** non-integer negative result: non-integer result is equivalent to
-** a non-zero remainder 'm'; negative result is equivalent to 'a' and
-** 'b' with different signs, or 'm' and 'b' with different signs
-** (as the result 'm' of 'fmod' has the same sign of 'a').
-*/
-#if !defined(luai_nummod)
-#define luai_nummod(L,a,b,m) \
- { (void)L; (m) = l_mathop(fmod)(a,b); \
- if (((m) > 0) ? (b) < 0 : ((m) < 0 && (b) > 0)) (m) += (b); }
-#endif
-
-/* exponentiation */
-#if !defined(luai_numpow)
-#define luai_numpow(L,a,b) \
- ((void)L, (b == 2) ? (a)*(a) : l_mathop(pow)(a,b))
-#endif
-
-/* the others are quite standard operations */
-#if !defined(luai_numadd)
-#define luai_numadd(L,a,b) ((void)L, (a)+(b))
-#define luai_numsub(L,a,b) ((void)L, (a)-(b))
-#define luai_nummul(L,a,b) ((void)L, (a)*(b))
-#define luai_numunm(L,a) ((void)L, -(a))
-#define luai_numeq(a,b) ((a)==(b))
-#define luai_numlt(a,b) ((a)<(b))
-#define luai_numle(a,b) ((a)<=(b))
-#define luai_numgt(a,b) ((a)>(b))
-#define luai_numge(a,b) ((a)>=(b))
-#define luai_numisnan(a) (!luai_numeq((a), (a)))
-#endif
-
-
-
-/*
-** lua_numbertointeger converts a float number with an integral value
-** to an integer, or returns 0 if the float is not within the range of
-** a lua_Integer. (The range comparisons are tricky because of
-** rounding. The tests here assume a two-complement representation,
-** where MININTEGER always has an exact representation as a float;
-** MAXINTEGER may not have one, and therefore its conversion to float
-** may have an ill-defined value.)
-*/
-#define lua_numbertointeger(n,p) \
- ((n) >= (LUA_NUMBER)(LUA_MININTEGER) && \
- (n) < -(LUA_NUMBER)(LUA_MININTEGER) && \
- (*(p) = (LUA_INTEGER)(n), 1))
-
-
-
-/*
-** LUAI_FUNC is a mark for all extern functions that are not to be
-** exported to outside modules.
-** LUAI_DDEF and LUAI_DDEC are marks for all extern (const) variables,
-** none of which to be exported to outside modules (LUAI_DDEF for
-** definitions and LUAI_DDEC for declarations).
-** Elf and MACH/gcc (versions 3.2 and later) mark them as "hidden" to
-** optimize access when Lua is compiled as a shared library. Not all elf
-** targets support this attribute. Unfortunately, gcc does not offer
-** a way to check whether the target offers that support, and those
-** without support give a warning about it. To avoid these warnings,
-** change to the default definition.
-*/
-#if !defined(LUAI_FUNC)
-
-#if defined(__GNUC__) && ((__GNUC__*100 + __GNUC_MINOR__) >= 302) && \
- (defined(__ELF__) || defined(__MACH__))
-#define LUAI_FUNC __attribute__((visibility("internal"))) extern
-#else
-#define LUAI_FUNC extern
-#endif
-
-#define LUAI_DDEC(dec) LUAI_FUNC dec
-#define LUAI_DDEF /* empty */
-
-#endif
-
-
-/* Give these macros simpler names for internal use */
-#define l_likely(x) luai_likely(x)
-#define l_unlikely(x) luai_unlikely(x)
-
-/*
-** {==================================================================
-** "Abstraction Layer" for basic report of messages and errors
-** ===================================================================
-*/
-
-/* print a string */
-#if !defined(lua_writestring)
-#define lua_writestring(s,l) fwrite((s), sizeof(char), (l), stdout)
-#endif
-
-/* print a newline and flush the output */
-#if !defined(lua_writeline)
-#define lua_writeline() (lua_writestring("\n", 1), fflush(stdout))
-#endif
-
-/* print an error message */
-#if !defined(lua_writestringerror)
-#define lua_writestringerror(s,p) \
- (fprintf(stderr, (s), (p)), fflush(stderr))
-#endif
-
-/* }================================================================== */
-
-#endif
-
diff --git a/lmathlib.c b/lmathlib.c
deleted file mode 100644
index a6b13f969c..0000000000
--- a/lmathlib.c
+++ /dev/null
@@ -1,765 +0,0 @@
-/*
-** $Id: lmathlib.c $
-** Standard mathematical library
-** See Copyright Notice in lua.h
-*/
-
-#define lmathlib_c
-#define LUA_LIB
-
-#include "lprefix.h"
-
-
-#include
-#include
-#include
-#include
-#include
-
-#include "lua.h"
-
-#include "lauxlib.h"
-#include "lualib.h"
-#include "llimits.h"
-
-
-#undef PI
-#define PI (l_mathop(3.141592653589793238462643383279502884))
-
-
-static int math_abs (lua_State *L) {
- if (lua_isinteger(L, 1)) {
- lua_Integer n = lua_tointeger(L, 1);
- if (n < 0) n = (lua_Integer)(0u - (lua_Unsigned)n);
- lua_pushinteger(L, n);
- }
- else
- lua_pushnumber(L, l_mathop(fabs)(luaL_checknumber(L, 1)));
- return 1;
-}
-
-
-static int math_sin (lua_State *L) {
- lua_pushnumber(L, l_mathop(sin)(luaL_checknumber(L, 1)));
- return 1;
-}
-
-
-static int math_cos (lua_State *L) {
- lua_pushnumber(L, l_mathop(cos)(luaL_checknumber(L, 1)));
- return 1;
-}
-
-
-static int math_tan (lua_State *L) {
- lua_pushnumber(L, l_mathop(tan)(luaL_checknumber(L, 1)));
- return 1;
-}
-
-
-static int math_asin (lua_State *L) {
- lua_pushnumber(L, l_mathop(asin)(luaL_checknumber(L, 1)));
- return 1;
-}
-
-
-static int math_acos (lua_State *L) {
- lua_pushnumber(L, l_mathop(acos)(luaL_checknumber(L, 1)));
- return 1;
-}
-
-
-static int math_atan (lua_State *L) {
- lua_Number y = luaL_checknumber(L, 1);
- lua_Number x = luaL_optnumber(L, 2, 1);
- lua_pushnumber(L, l_mathop(atan2)(y, x));
- return 1;
-}
-
-
-static int math_toint (lua_State *L) {
- int valid;
- lua_Integer n = lua_tointegerx(L, 1, &valid);
- if (l_likely(valid))
- lua_pushinteger(L, n);
- else {
- luaL_checkany(L, 1);
- luaL_pushfail(L); /* value is not convertible to integer */
- }
- return 1;
-}
-
-
-static void pushnumint (lua_State *L, lua_Number d) {
- lua_Integer n;
- if (lua_numbertointeger(d, &n)) /* does 'd' fit in an integer? */
- lua_pushinteger(L, n); /* result is integer */
- else
- lua_pushnumber(L, d); /* result is float */
-}
-
-
-static int math_floor (lua_State *L) {
- if (lua_isinteger(L, 1))
- lua_settop(L, 1); /* integer is its own floor */
- else {
- lua_Number d = l_mathop(floor)(luaL_checknumber(L, 1));
- pushnumint(L, d);
- }
- return 1;
-}
-
-
-static int math_ceil (lua_State *L) {
- if (lua_isinteger(L, 1))
- lua_settop(L, 1); /* integer is its own ceiling */
- else {
- lua_Number d = l_mathop(ceil)(luaL_checknumber(L, 1));
- pushnumint(L, d);
- }
- return 1;
-}
-
-
-static int math_fmod (lua_State *L) {
- if (lua_isinteger(L, 1) && lua_isinteger(L, 2)) {
- lua_Integer d = lua_tointeger(L, 2);
- if ((lua_Unsigned)d + 1u <= 1u) { /* special cases: -1 or 0 */
- luaL_argcheck(L, d != 0, 2, "zero");
- lua_pushinteger(L, 0); /* avoid overflow with 0x80000... / -1 */
- }
- else
- lua_pushinteger(L, lua_tointeger(L, 1) % d);
- }
- else
- lua_pushnumber(L, l_mathop(fmod)(luaL_checknumber(L, 1),
- luaL_checknumber(L, 2)));
- return 1;
-}
-
-
-/*
-** next function does not use 'modf', avoiding problems with 'double*'
-** (which is not compatible with 'float*') when lua_Number is not
-** 'double'.
-*/
-static int math_modf (lua_State *L) {
- if (lua_isinteger(L ,1)) {
- lua_settop(L, 1); /* number is its own integer part */
- lua_pushnumber(L, 0); /* no fractional part */
- }
- else {
- lua_Number n = luaL_checknumber(L, 1);
- /* integer part (rounds toward zero) */
- lua_Number ip = (n < 0) ? l_mathop(ceil)(n) : l_mathop(floor)(n);
- pushnumint(L, ip);
- /* fractional part (test needed for inf/-inf) */
- lua_pushnumber(L, (n == ip) ? l_mathop(0.0) : (n - ip));
- }
- return 2;
-}
-
-
-static int math_sqrt (lua_State *L) {
- lua_pushnumber(L, l_mathop(sqrt)(luaL_checknumber(L, 1)));
- return 1;
-}
-
-
-static int math_ult (lua_State *L) {
- lua_Integer a = luaL_checkinteger(L, 1);
- lua_Integer b = luaL_checkinteger(L, 2);
- lua_pushboolean(L, (lua_Unsigned)a < (lua_Unsigned)b);
- return 1;
-}
-
-
-static int math_log (lua_State *L) {
- lua_Number x = luaL_checknumber(L, 1);
- lua_Number res;
- if (lua_isnoneornil(L, 2))
- res = l_mathop(log)(x);
- else {
- lua_Number base = luaL_checknumber(L, 2);
-#if !defined(LUA_USE_C89)
- if (base == l_mathop(2.0))
- res = l_mathop(log2)(x);
- else
-#endif
- if (base == l_mathop(10.0))
- res = l_mathop(log10)(x);
- else
- res = l_mathop(log)(x)/l_mathop(log)(base);
- }
- lua_pushnumber(L, res);
- return 1;
-}
-
-
-static int math_exp (lua_State *L) {
- lua_pushnumber(L, l_mathop(exp)(luaL_checknumber(L, 1)));
- return 1;
-}
-
-
-static int math_deg (lua_State *L) {
- lua_pushnumber(L, luaL_checknumber(L, 1) * (l_mathop(180.0) / PI));
- return 1;
-}
-
-
-static int math_rad (lua_State *L) {
- lua_pushnumber(L, luaL_checknumber(L, 1) * (PI / l_mathop(180.0)));
- return 1;
-}
-
-
-static int math_frexp (lua_State *L) {
- lua_Number x = luaL_checknumber(L, 1);
- int ep;
- lua_pushnumber(L, l_mathop(frexp)(x, &ep));
- lua_pushinteger(L, ep);
- return 2;
-}
-
-
-static int math_ldexp (lua_State *L) {
- lua_Number x = luaL_checknumber(L, 1);
- int ep = (int)luaL_checkinteger(L, 2);
- lua_pushnumber(L, l_mathop(ldexp)(x, ep));
- return 1;
-}
-
-
-static int math_min (lua_State *L) {
- int n = lua_gettop(L); /* number of arguments */
- int imin = 1; /* index of current minimum value */
- int i;
- luaL_argcheck(L, n >= 1, 1, "value expected");
- for (i = 2; i <= n; i++) {
- if (lua_compare(L, i, imin, LUA_OPLT))
- imin = i;
- }
- lua_pushvalue(L, imin);
- return 1;
-}
-
-
-static int math_max (lua_State *L) {
- int n = lua_gettop(L); /* number of arguments */
- int imax = 1; /* index of current maximum value */
- int i;
- luaL_argcheck(L, n >= 1, 1, "value expected");
- for (i = 2; i <= n; i++) {
- if (lua_compare(L, imax, i, LUA_OPLT))
- imax = i;
- }
- lua_pushvalue(L, imax);
- return 1;
-}
-
-
-static int math_type (lua_State *L) {
- if (lua_type(L, 1) == LUA_TNUMBER)
- lua_pushstring(L, (lua_isinteger(L, 1)) ? "integer" : "float");
- else {
- luaL_checkany(L, 1);
- luaL_pushfail(L);
- }
- return 1;
-}
-
-
-
-/*
-** {==================================================================
-** Pseudo-Random Number Generator based on 'xoshiro256**'.
-** ===================================================================
-*/
-
-/*
-** This code uses lots of shifts. ISO C does not allow shifts greater
-** than or equal to the width of the type being shifted, so some shifts
-** are written in convoluted ways to match that restriction. For
-** preprocessor tests, it assumes a width of 32 bits, so the maximum
-** shift there is 31 bits.
-*/
-
-
-/* number of binary digits in the mantissa of a float */
-#define FIGS l_floatatt(MANT_DIG)
-
-#if FIGS > 64
-/* there are only 64 random bits; use them all */
-#undef FIGS
-#define FIGS 64
-#endif
-
-
-/*
-** LUA_RAND32 forces the use of 32-bit integers in the implementation
-** of the PRN generator (mainly for testing).
-*/
-#if !defined(LUA_RAND32) && !defined(Rand64)
-
-/* try to find an integer type with at least 64 bits */
-
-#if ((ULONG_MAX >> 31) >> 31) >= 3
-
-/* 'long' has at least 64 bits */
-#define Rand64 unsigned long
-#define SRand64 long
-
-#elif !defined(LUA_USE_C89) && defined(LLONG_MAX)
-
-/* there is a 'long long' type (which must have at least 64 bits) */
-#define Rand64 unsigned long long
-#define SRand64 long long
-
-#elif ((LUA_MAXUNSIGNED >> 31) >> 31) >= 3
-
-/* 'lua_Unsigned' has at least 64 bits */
-#define Rand64 lua_Unsigned
-#define SRand64 lua_Integer
-
-#endif
-
-#endif
-
-
-#if defined(Rand64) /* { */
-
-/*
-** Standard implementation, using 64-bit integers.
-** If 'Rand64' has more than 64 bits, the extra bits do not interfere
-** with the 64 initial bits, except in a right shift. Moreover, the
-** final result has to discard the extra bits.
-*/
-
-/* avoid using extra bits when needed */
-#define trim64(x) ((x) & 0xffffffffffffffffu)
-
-
-/* rotate left 'x' by 'n' bits */
-static Rand64 rotl (Rand64 x, int n) {
- return (x << n) | (trim64(x) >> (64 - n));
-}
-
-static Rand64 nextrand (Rand64 *state) {
- Rand64 state0 = state[0];
- Rand64 state1 = state[1];
- Rand64 state2 = state[2] ^ state0;
- Rand64 state3 = state[3] ^ state1;
- Rand64 res = rotl(state1 * 5, 7) * 9;
- state[0] = state0 ^ state3;
- state[1] = state1 ^ state2;
- state[2] = state2 ^ (state1 << 17);
- state[3] = rotl(state3, 45);
- return res;
-}
-
-
-/*
-** Convert bits from a random integer into a float in the
-** interval [0,1), getting the higher FIG bits from the
-** random unsigned integer and converting that to a float.
-** Some old Microsoft compilers cannot cast an unsigned long
-** to a floating-point number, so we use a signed long as an
-** intermediary. When lua_Number is float or double, the shift ensures
-** that 'sx' is non negative; in that case, a good compiler will remove
-** the correction.
-*/
-
-/* must throw out the extra (64 - FIGS) bits */
-#define shift64_FIG (64 - FIGS)
-
-/* 2^(-FIGS) == 2^-1 / 2^(FIGS-1) */
-#define scaleFIG (l_mathop(0.5) / ((Rand64)1 << (FIGS - 1)))
-
-static lua_Number I2d (Rand64 x) {
- SRand64 sx = (SRand64)(trim64(x) >> shift64_FIG);
- lua_Number res = (lua_Number)(sx) * scaleFIG;
- if (sx < 0)
- res += l_mathop(1.0); /* correct the two's complement if negative */
- lua_assert(0 <= res && res < 1);
- return res;
-}
-
-/* convert a 'Rand64' to a 'lua_Unsigned' */
-#define I2UInt(x) ((lua_Unsigned)trim64(x))
-
-/* convert a 'lua_Unsigned' to a 'Rand64' */
-#define Int2I(x) ((Rand64)(x))
-
-
-#else /* no 'Rand64' }{ */
-
-/*
-** Use two 32-bit integers to represent a 64-bit quantity.
-*/
-typedef struct Rand64 {
- l_uint32 h; /* higher half */
- l_uint32 l; /* lower half */
-} Rand64;
-
-
-/*
-** If 'l_uint32' has more than 32 bits, the extra bits do not interfere
-** with the 32 initial bits, except in a right shift and comparisons.
-** Moreover, the final result has to discard the extra bits.
-*/
-
-/* avoid using extra bits when needed */
-#define trim32(x) ((x) & 0xffffffffu)
-
-
-/*
-** basic operations on 'Rand64' values
-*/
-
-/* build a new Rand64 value */
-static Rand64 packI (l_uint32 h, l_uint32 l) {
- Rand64 result;
- result.h = h;
- result.l = l;
- return result;
-}
-
-/* return i << n */
-static Rand64 Ishl (Rand64 i, int n) {
- lua_assert(n > 0 && n < 32);
- return packI((i.h << n) | (trim32(i.l) >> (32 - n)), i.l << n);
-}
-
-/* i1 ^= i2 */
-static void Ixor (Rand64 *i1, Rand64 i2) {
- i1->h ^= i2.h;
- i1->l ^= i2.l;
-}
-
-/* return i1 + i2 */
-static Rand64 Iadd (Rand64 i1, Rand64 i2) {
- Rand64 result = packI(i1.h + i2.h, i1.l + i2.l);
- if (trim32(result.l) < trim32(i1.l)) /* carry? */
- result.h++;
- return result;
-}
-
-/* return i * 5 */
-static Rand64 times5 (Rand64 i) {
- return Iadd(Ishl(i, 2), i); /* i * 5 == (i << 2) + i */
-}
-
-/* return i * 9 */
-static Rand64 times9 (Rand64 i) {
- return Iadd(Ishl(i, 3), i); /* i * 9 == (i << 3) + i */
-}
-
-/* return 'i' rotated left 'n' bits */
-static Rand64 rotl (Rand64 i, int n) {
- lua_assert(n > 0 && n < 32);
- return packI((i.h << n) | (trim32(i.l) >> (32 - n)),
- (trim32(i.h) >> (32 - n)) | (i.l << n));
-}
-
-/* for offsets larger than 32, rotate right by 64 - offset */
-static Rand64 rotl1 (Rand64 i, int n) {
- lua_assert(n > 32 && n < 64);
- n = 64 - n;
- return packI((trim32(i.h) >> n) | (i.l << (32 - n)),
- (i.h << (32 - n)) | (trim32(i.l) >> n));
-}
-
-/*
-** implementation of 'xoshiro256**' algorithm on 'Rand64' values
-*/
-static Rand64 nextrand (Rand64 *state) {
- Rand64 res = times9(rotl(times5(state[1]), 7));
- Rand64 t = Ishl(state[1], 17);
- Ixor(&state[2], state[0]);
- Ixor(&state[3], state[1]);
- Ixor(&state[1], state[2]);
- Ixor(&state[0], state[3]);
- Ixor(&state[2], t);
- state[3] = rotl1(state[3], 45);
- return res;
-}
-
-
-/*
-** Converts a 'Rand64' into a float.
-*/
-
-/* an unsigned 1 with proper type */
-#define UONE ((l_uint32)1)
-
-
-#if FIGS <= 32
-
-/* 2^(-FIGS) */
-#define scaleFIG (l_mathop(0.5) / (UONE << (FIGS - 1)))
-
-/*
-** get up to 32 bits from higher half, shifting right to
-** throw out the extra bits.
-*/
-static lua_Number I2d (Rand64 x) {
- lua_Number h = (lua_Number)(trim32(x.h) >> (32 - FIGS));
- return h * scaleFIG;
-}
-
-#else /* 32 < FIGS <= 64 */
-
-/* 2^(-FIGS) = 1.0 / 2^30 / 2^3 / 2^(FIGS-33) */
-#define scaleFIG \
- (l_mathop(1.0) / (UONE << 30) / l_mathop(8.0) / (UONE << (FIGS - 33)))
-
-/*
-** use FIGS - 32 bits from lower half, throwing out the other
-** (32 - (FIGS - 32)) = (64 - FIGS) bits
-*/
-#define shiftLOW (64 - FIGS)
-
-/*
-** higher 32 bits go after those (FIGS - 32) bits: shiftHI = 2^(FIGS - 32)
-*/
-#define shiftHI ((lua_Number)(UONE << (FIGS - 33)) * l_mathop(2.0))
-
-
-static lua_Number I2d (Rand64 x) {
- lua_Number h = (lua_Number)trim32(x.h) * shiftHI;
- lua_Number l = (lua_Number)(trim32(x.l) >> shiftLOW);
- return (h + l) * scaleFIG;
-}
-
-#endif
-
-
-/* convert a 'Rand64' to a 'lua_Unsigned' */
-static lua_Unsigned I2UInt (Rand64 x) {
- return (((lua_Unsigned)trim32(x.h) << 31) << 1) | (lua_Unsigned)trim32(x.l);
-}
-
-/* convert a 'lua_Unsigned' to a 'Rand64' */
-static Rand64 Int2I (lua_Unsigned n) {
- return packI((l_uint32)((n >> 31) >> 1), (l_uint32)n);
-}
-
-#endif /* } */
-
-
-/*
-** A state uses four 'Rand64' values.
-*/
-typedef struct {
- Rand64 s[4];
-} RanState;
-
-
-/*
-** Project the random integer 'ran' into the interval [0, n].
-** Because 'ran' has 2^B possible values, the projection can only be
-** uniform when the size of the interval is a power of 2 (exact
-** division). So, to get a uniform projection into [0, n], we
-** first compute 'lim', the smallest Mersenne number not smaller than
-** 'n'. We then project 'ran' into the interval [0, lim]. If the result
-** is inside [0, n], we are done. Otherwise, we try with another 'ran',
-** until we have a result inside the interval.
-*/
-static lua_Unsigned project (lua_Unsigned ran, lua_Unsigned n,
- RanState *state) {
- lua_Unsigned lim = n; /* to compute the Mersenne number */
- int sh; /* how much to spread bits to the right in 'lim' */
- /* spread '1' bits in 'lim' until it becomes a Mersenne number */
- for (sh = 1; (lim & (lim + 1)) != 0; sh *= 2)
- lim |= (lim >> sh); /* spread '1's to the right */
- while ((ran &= lim) > n) /* project 'ran' into [0..lim] and test */
- ran = I2UInt(nextrand(state->s)); /* not inside [0..n]? try again */
- return ran;
-}
-
-
-static int math_random (lua_State *L) {
- lua_Integer low, up;
- lua_Unsigned p;
- RanState *state = (RanState *)lua_touserdata(L, lua_upvalueindex(1));
- Rand64 rv = nextrand(state->s); /* next pseudo-random value */
- switch (lua_gettop(L)) { /* check number of arguments */
- case 0: { /* no arguments */
- lua_pushnumber(L, I2d(rv)); /* float between 0 and 1 */
- return 1;
- }
- case 1: { /* only upper limit */
- low = 1;
- up = luaL_checkinteger(L, 1);
- if (up == 0) { /* single 0 as argument? */
- lua_pushinteger(L, l_castU2S(I2UInt(rv))); /* full random integer */
- return 1;
- }
- break;
- }
- case 2: { /* lower and upper limits */
- low = luaL_checkinteger(L, 1);
- up = luaL_checkinteger(L, 2);
- break;
- }
- default: return luaL_error(L, "wrong number of arguments");
- }
- /* random integer in the interval [low, up] */
- luaL_argcheck(L, low <= up, 1, "interval is empty");
- /* project random integer into the interval [0, up - low] */
- p = project(I2UInt(rv), l_castS2U(up) - l_castS2U(low), state);
- lua_pushinteger(L, l_castU2S(p + l_castS2U(low)));
- return 1;
-}
-
-
-static void setseed (lua_State *L, Rand64 *state,
- lua_Unsigned n1, lua_Unsigned n2) {
- int i;
- state[0] = Int2I(n1);
- state[1] = Int2I(0xff); /* avoid a zero state */
- state[2] = Int2I(n2);
- state[3] = Int2I(0);
- for (i = 0; i < 16; i++)
- nextrand(state); /* discard initial values to "spread" seed */
- lua_pushinteger(L, l_castU2S(n1));
- lua_pushinteger(L, l_castU2S(n2));
-}
-
-
-static int math_randomseed (lua_State *L) {
- RanState *state = (RanState *)lua_touserdata(L, lua_upvalueindex(1));
- lua_Unsigned n1, n2;
- if (lua_isnone(L, 1)) {
- n1 = luaL_makeseed(L); /* "random" seed */
- n2 = I2UInt(nextrand(state->s)); /* in case seed is not that random... */
- }
- else {
- n1 = l_castS2U(luaL_checkinteger(L, 1));
- n2 = l_castS2U(luaL_optinteger(L, 2, 0));
- }
- setseed(L, state->s, n1, n2);
- return 2; /* return seeds */
-}
-
-
-static const luaL_Reg randfuncs[] = {
- {"random", math_random},
- {"randomseed", math_randomseed},
- {NULL, NULL}
-};
-
-
-/*
-** Register the random functions and initialize their state.
-*/
-static void setrandfunc (lua_State *L) {
- RanState *state = (RanState *)lua_newuserdatauv(L, sizeof(RanState), 0);
- setseed(L, state->s, luaL_makeseed(L), 0); /* initialize with random seed */
- lua_pop(L, 2); /* remove pushed seeds */
- luaL_setfuncs(L, randfuncs, 1);
-}
-
-/* }================================================================== */
-
-
-/*
-** {==================================================================
-** Deprecated functions (for compatibility only)
-** ===================================================================
-*/
-#if defined(LUA_COMPAT_MATHLIB)
-
-static int math_cosh (lua_State *L) {
- lua_pushnumber(L, l_mathop(cosh)(luaL_checknumber(L, 1)));
- return 1;
-}
-
-static int math_sinh (lua_State *L) {
- lua_pushnumber(L, l_mathop(sinh)(luaL_checknumber(L, 1)));
- return 1;
-}
-
-static int math_tanh (lua_State *L) {
- lua_pushnumber(L, l_mathop(tanh)(luaL_checknumber(L, 1)));
- return 1;
-}
-
-static int math_pow (lua_State *L) {
- lua_Number x = luaL_checknumber(L, 1);
- lua_Number y = luaL_checknumber(L, 2);
- lua_pushnumber(L, l_mathop(pow)(x, y));
- return 1;
-}
-
-static int math_log10 (lua_State *L) {
- lua_pushnumber(L, l_mathop(log10)(luaL_checknumber(L, 1)));
- return 1;
-}
-
-#endif
-/* }================================================================== */
-
-
-
-static const luaL_Reg mathlib[] = {
- {"abs", math_abs},
- {"acos", math_acos},
- {"asin", math_asin},
- {"atan", math_atan},
- {"ceil", math_ceil},
- {"cos", math_cos},
- {"deg", math_deg},
- {"exp", math_exp},
- {"tointeger", math_toint},
- {"floor", math_floor},
- {"fmod", math_fmod},
- {"frexp", math_frexp},
- {"ult", math_ult},
- {"ldexp", math_ldexp},
- {"log", math_log},
- {"max", math_max},
- {"min", math_min},
- {"modf", math_modf},
- {"rad", math_rad},
- {"sin", math_sin},
- {"sqrt", math_sqrt},
- {"tan", math_tan},
- {"type", math_type},
-#if defined(LUA_COMPAT_MATHLIB)
- {"atan2", math_atan},
- {"cosh", math_cosh},
- {"sinh", math_sinh},
- {"tanh", math_tanh},
- {"pow", math_pow},
- {"log10", math_log10},
-#endif
- /* placeholders */
- {"random", NULL},
- {"randomseed", NULL},
- {"pi", NULL},
- {"huge", NULL},
- {"maxinteger", NULL},
- {"mininteger", NULL},
- {NULL, NULL}
-};
-
-
-/*
-** Open math library
-*/
-LUAMOD_API int luaopen_math (lua_State *L) {
- luaL_newlib(L, mathlib);
- lua_pushnumber(L, PI);
- lua_setfield(L, -2, "pi");
- lua_pushnumber(L, (lua_Number)HUGE_VAL);
- lua_setfield(L, -2, "huge");
- lua_pushinteger(L, LUA_MAXINTEGER);
- lua_setfield(L, -2, "maxinteger");
- lua_pushinteger(L, LUA_MININTEGER);
- lua_setfield(L, -2, "mininteger");
- setrandfunc(L);
- return 1;
-}
-
diff --git a/lmem.c b/lmem.c
deleted file mode 100644
index de8503d91b..0000000000
--- a/lmem.c
+++ /dev/null
@@ -1,215 +0,0 @@
-/*
-** $Id: lmem.c $
-** Interface to Memory Manager
-** See Copyright Notice in lua.h
-*/
-
-#define lmem_c
-#define LUA_CORE
-
-#include "lprefix.h"
-
-
-#include
-
-#include "lua.h"
-
-#include "ldebug.h"
-#include "ldo.h"
-#include "lgc.h"
-#include "lmem.h"
-#include "lobject.h"
-#include "lstate.h"
-
-
-
-/*
-** About the realloc function:
-** void *frealloc (void *ud, void *ptr, size_t osize, size_t nsize);
-** ('osize' is the old size, 'nsize' is the new size)
-**
-** - frealloc(ud, p, x, 0) frees the block 'p' and returns NULL.
-** Particularly, frealloc(ud, NULL, 0, 0) does nothing,
-** which is equivalent to free(NULL) in ISO C.
-**
-** - frealloc(ud, NULL, x, s) creates a new block of size 's'
-** (no matter 'x'). Returns NULL if it cannot create the new block.
-**
-** - otherwise, frealloc(ud, b, x, y) reallocates the block 'b' from
-** size 'x' to size 'y'. Returns NULL if it cannot reallocate the
-** block to the new size.
-*/
-
-
-/*
-** Macro to call the allocation function.
-*/
-#define callfrealloc(g,block,os,ns) ((*g->frealloc)(g->ud, block, os, ns))
-
-
-/*
-** When an allocation fails, it will try again after an emergency
-** collection, except when it cannot run a collection. The GC should
-** not be called while the state is not fully built, as the collector
-** is not yet fully initialized. Also, it should not be called when
-** 'gcstopem' is true, because then the interpreter is in the middle of
-** a collection step.
-*/
-#define cantryagain(g) (completestate(g) && !g->gcstopem)
-
-
-
-
-#if defined(EMERGENCYGCTESTS)
-/*
-** First allocation will fail except when freeing a block (frees never
-** fail) and when it cannot try again; this fail will trigger 'tryagain'
-** and a full GC cycle at every allocation.
-*/
-static void *firsttry (global_State *g, void *block, size_t os, size_t ns) {
- if (ns > 0 && cantryagain(g))
- return NULL; /* fail */
- else /* normal allocation */
- return callfrealloc(g, block, os, ns);
-}
-#else
-#define firsttry(g,block,os,ns) callfrealloc(g, block, os, ns)
-#endif
-
-
-
-
-
-/*
-** {==================================================================
-** Functions to allocate/deallocate arrays for the Parser
-** ===================================================================
-*/
-
-/*
-** Minimum size for arrays during parsing, to avoid overhead of
-** reallocating to size 1, then 2, and then 4. All these arrays
-** will be reallocated to exact sizes or erased when parsing ends.
-*/
-#define MINSIZEARRAY 4
-
-
-void *luaM_growaux_ (lua_State *L, void *block, int nelems, int *psize,
- unsigned size_elems, int limit, const char *what) {
- void *newblock;
- int size = *psize;
- if (nelems + 1 <= size) /* does one extra element still fit? */
- return block; /* nothing to be done */
- if (size >= limit / 2) { /* cannot double it? */
- if (l_unlikely(size >= limit)) /* cannot grow even a little? */
- luaG_runerror(L, "too many %s (limit is %d)", what, limit);
- size = limit; /* still have at least one free place */
- }
- else {
- size *= 2;
- if (size < MINSIZEARRAY)
- size = MINSIZEARRAY; /* minimum size */
- }
- lua_assert(nelems + 1 <= size && size <= limit);
- /* 'limit' ensures that multiplication will not overflow */
- newblock = luaM_saferealloc_(L, block, cast_sizet(*psize) * size_elems,
- cast_sizet(size) * size_elems);
- *psize = size; /* update only when everything else is OK */
- return newblock;
-}
-
-
-/*
-** In prototypes, the size of the array is also its number of
-** elements (to save memory). So, if it cannot shrink an array
-** to its number of elements, the only option is to raise an
-** error.
-*/
-void *luaM_shrinkvector_ (lua_State *L, void *block, int *size,
- int final_n, unsigned size_elem) {
- void *newblock;
- size_t oldsize = cast_sizet(*size) * size_elem;
- size_t newsize = cast_sizet(final_n) * size_elem;
- lua_assert(newsize <= oldsize);
- newblock = luaM_saferealloc_(L, block, oldsize, newsize);
- *size = final_n;
- return newblock;
-}
-
-/* }================================================================== */
-
-
-l_noret luaM_toobig (lua_State *L) {
- luaG_runerror(L, "memory allocation error: block too big");
-}
-
-
-/*
-** Free memory
-*/
-void luaM_free_ (lua_State *L, void *block, size_t osize) {
- global_State *g = G(L);
- lua_assert((osize == 0) == (block == NULL));
- callfrealloc(g, block, osize, 0);
- g->GCdebt += cast(l_mem, osize);
-}
-
-
-/*
-** In case of allocation fail, this function will do an emergency
-** collection to free some memory and then try the allocation again.
-*/
-static void *tryagain (lua_State *L, void *block,
- size_t osize, size_t nsize) {
- global_State *g = G(L);
- if (cantryagain(g)) {
- luaC_fullgc(L, 1); /* try to free some memory... */
- return callfrealloc(g, block, osize, nsize); /* try again */
- }
- else return NULL; /* cannot run an emergency collection */
-}
-
-
-/*
-** Generic allocation routine.
-*/
-void *luaM_realloc_ (lua_State *L, void *block, size_t osize, size_t nsize) {
- void *newblock;
- global_State *g = G(L);
- lua_assert((osize == 0) == (block == NULL));
- newblock = firsttry(g, block, osize, nsize);
- if (l_unlikely(newblock == NULL && nsize > 0)) {
- newblock = tryagain(L, block, osize, nsize);
- if (newblock == NULL) /* still no memory? */
- return NULL; /* do not update 'GCdebt' */
- }
- lua_assert((nsize == 0) == (newblock == NULL));
- g->GCdebt -= cast(l_mem, nsize) - cast(l_mem, osize);
- return newblock;
-}
-
-
-void *luaM_saferealloc_ (lua_State *L, void *block, size_t osize,
- size_t nsize) {
- void *newblock = luaM_realloc_(L, block, osize, nsize);
- if (l_unlikely(newblock == NULL && nsize > 0)) /* allocation failed? */
- luaM_error(L);
- return newblock;
-}
-
-
-void *luaM_malloc_ (lua_State *L, size_t size, int tag) {
- if (size == 0)
- return NULL; /* that's all */
- else {
- global_State *g = G(L);
- void *newblock = firsttry(g, NULL, cast_sizet(tag), size);
- if (l_unlikely(newblock == NULL)) {
- newblock = tryagain(L, NULL, cast_sizet(tag), size);
- if (newblock == NULL)
- luaM_error(L);
- }
- g->GCdebt -= cast(l_mem, size);
- return newblock;
- }
-}
diff --git a/lmem.h b/lmem.h
deleted file mode 100644
index dc714fb2e4..0000000000
--- a/lmem.h
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
-** $Id: lmem.h $
-** Interface to Memory Manager
-** See Copyright Notice in lua.h
-*/
-
-#ifndef lmem_h
-#define lmem_h
-
-
-#include
-
-#include "llimits.h"
-#include "lua.h"
-
-
-#define luaM_error(L) luaD_throw(L, LUA_ERRMEM)
-
-
-/*
-** This macro tests whether it is safe to multiply 'n' by the size of
-** type 't' without overflows. Because 'e' is always constant, it avoids
-** the runtime division MAX_SIZET/(e).
-** (The macro is somewhat complex to avoid warnings: The 'sizeof'
-** comparison avoids a runtime comparison when overflow cannot occur.
-** The compiler should be able to optimize the real test by itself, but
-** when it does it, it may give a warning about "comparison is always
-** false due to limited range of data type"; the +1 tricks the compiler,
-** avoiding this warning but also this optimization.)
-*/
-#define luaM_testsize(n,e) \
- (sizeof(n) >= sizeof(size_t) && cast_sizet((n)) + 1 > MAX_SIZET/(e))
-
-#define luaM_checksize(L,n,e) \
- (luaM_testsize(n,e) ? luaM_toobig(L) : cast_void(0))
-
-
-/*
-** Computes the minimum between 'n' and 'MAX_SIZET/sizeof(t)', so that
-** the result is not larger than 'n' and cannot overflow a 'size_t'
-** when multiplied by the size of type 't'. (Assumes that 'n' is an
-** 'int' and that 'int' is not larger than 'size_t'.)
-*/
-#define luaM_limitN(n,t) \
- ((cast_sizet(n) <= MAX_SIZET/sizeof(t)) ? (n) : \
- cast_int((MAX_SIZET/sizeof(t))))
-
-
-/*
-** Arrays of chars do not need any test
-*/
-#define luaM_reallocvchar(L,b,on,n) \
- cast_charp(luaM_saferealloc_(L, (b), (on)*sizeof(char), (n)*sizeof(char)))
-
-#define luaM_freemem(L, b, s) luaM_free_(L, (b), (s))
-#define luaM_free(L, b) luaM_free_(L, (b), sizeof(*(b)))
-#define luaM_freearray(L, b, n) luaM_free_(L, (b), (n)*sizeof(*(b)))
-
-#define luaM_new(L,t) cast(t*, luaM_malloc_(L, sizeof(t), 0))
-#define luaM_newvector(L,n,t) \
- cast(t*, luaM_malloc_(L, cast_sizet(n)*sizeof(t), 0))
-#define luaM_newvectorchecked(L,n,t) \
- (luaM_checksize(L,n,sizeof(t)), luaM_newvector(L,n,t))
-
-#define luaM_newobject(L,tag,s) luaM_malloc_(L, (s), tag)
-
-#define luaM_newblock(L, size) luaM_newvector(L, size, char)
-
-#define luaM_growvector(L,v,nelems,size,t,limit,e) \
- ((v)=cast(t *, luaM_growaux_(L,v,nelems,&(size),sizeof(t), \
- luaM_limitN(limit,t),e)))
-
-#define luaM_reallocvector(L, v,oldn,n,t) \
- (cast(t *, luaM_realloc_(L, v, cast_sizet(oldn) * sizeof(t), \
- cast_sizet(n) * sizeof(t))))
-
-#define luaM_shrinkvector(L,v,size,fs,t) \
- ((v)=cast(t *, luaM_shrinkvector_(L, v, &(size), fs, sizeof(t))))
-
-LUAI_FUNC l_noret luaM_toobig (lua_State *L);
-
-/* not to be called directly */
-LUAI_FUNC void *luaM_realloc_ (lua_State *L, void *block, size_t oldsize,
- size_t size);
-LUAI_FUNC void *luaM_saferealloc_ (lua_State *L, void *block, size_t oldsize,
- size_t size);
-LUAI_FUNC void luaM_free_ (lua_State *L, void *block, size_t osize);
-LUAI_FUNC void *luaM_growaux_ (lua_State *L, void *block, int nelems,
- int *size, unsigned size_elem, int limit,
- const char *what);
-LUAI_FUNC void *luaM_shrinkvector_ (lua_State *L, void *block, int *nelem,
- int final_n, unsigned size_elem);
-LUAI_FUNC void *luaM_malloc_ (lua_State *L, size_t size, int tag);
-
-#endif
-
diff --git a/lobject.c b/lobject.c
deleted file mode 100644
index 763b484609..0000000000
--- a/lobject.c
+++ /dev/null
@@ -1,718 +0,0 @@
-/*
-** $Id: lobject.c $
-** Some generic functions over Lua objects
-** See Copyright Notice in lua.h
-*/
-
-#define lobject_c
-#define LUA_CORE
-
-#include "lprefix.h"
-
-
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-
-#include "lua.h"
-
-#include "lctype.h"
-#include "ldebug.h"
-#include "ldo.h"
-#include "lmem.h"
-#include "lobject.h"
-#include "lstate.h"
-#include "lstring.h"
-#include "lvm.h"
-
-
-/*
-** Computes ceil(log2(x)), which is the smallest integer n such that
-** x <= (1 << n).
-*/
-lu_byte luaO_ceillog2 (unsigned int x) {
- static const lu_byte log_2[256] = { /* log_2[i - 1] = ceil(log2(i)) */
- 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
- 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
- 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
- 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
- 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
- 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
- 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
- 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8
- };
- int l = 0;
- x--;
- while (x >= 256) { l += 8; x >>= 8; }
- return cast_byte(l + log_2[x]);
-}
-
-/*
-** Encodes 'p'% as a floating-point byte, represented as (eeeexxxx).
-** The exponent is represented using excess-7. Mimicking IEEE 754, the
-** representation normalizes the number when possible, assuming an extra
-** 1 before the mantissa (xxxx) and adding one to the exponent (eeee)
-** to signal that. So, the real value is (1xxxx) * 2^(eeee - 7 - 1) if
-** eeee != 0, and (xxxx) * 2^-7 otherwise (subnormal numbers).
-*/
-lu_byte luaO_codeparam (unsigned int p) {
- if (p >= (cast(lu_mem, 0x1F) << (0xF - 7 - 1)) * 100u) /* overflow? */
- return 0xFF; /* return maximum value */
- else {
- p = (cast(l_uint32, p) * 128 + 99) / 100; /* round up the division */
- if (p < 0x10) { /* subnormal number? */
- /* exponent bits are already zero; nothing else to do */
- return cast_byte(p);
- }
- else { /* p >= 0x10 implies ceil(log2(p + 1)) >= 5 */
- /* preserve 5 bits in 'p' */
- unsigned log = luaO_ceillog2(p + 1) - 5u;
- return cast_byte(((p >> log) - 0x10) | ((log + 1) << 4));
- }
- }
-}
-
-
-/*
-** Computes 'p' times 'x', where 'p' is a floating-point byte. Roughly,
-** we have to multiply 'x' by the mantissa and then shift accordingly to
-** the exponent. If the exponent is positive, both the multiplication
-** and the shift increase 'x', so we have to care only about overflows.
-** For negative exponents, however, multiplying before the shift keeps
-** more significant bits, as long as the multiplication does not
-** overflow, so we check which order is best.
-*/
-l_mem luaO_applyparam (lu_byte p, l_mem x) {
- int m = p & 0xF; /* mantissa */
- int e = (p >> 4); /* exponent */
- if (e > 0) { /* normalized? */
- e--; /* correct exponent */
- m += 0x10; /* correct mantissa; maximum value is 0x1F */
- }
- e -= 7; /* correct excess-7 */
- if (e >= 0) {
- if (x < (MAX_LMEM / 0x1F) >> e) /* no overflow? */
- return (x * m) << e; /* order doesn't matter here */
- else /* real overflow */
- return MAX_LMEM;
- }
- else { /* negative exponent */
- e = -e;
- if (x < MAX_LMEM / 0x1F) /* multiplication cannot overflow? */
- return (x * m) >> e; /* multiplying first gives more precision */
- else if ((x >> e) < MAX_LMEM / 0x1F) /* cannot overflow after shift? */
- return (x >> e) * m;
- else /* real overflow */
- return MAX_LMEM;
- }
-}
-
-
-static lua_Integer intarith (lua_State *L, int op, lua_Integer v1,
- lua_Integer v2) {
- switch (op) {
- case LUA_OPADD: return intop(+, v1, v2);
- case LUA_OPSUB:return intop(-, v1, v2);
- case LUA_OPMUL:return intop(*, v1, v2);
- case LUA_OPMOD: return luaV_mod(L, v1, v2);
- case LUA_OPIDIV: return luaV_idiv(L, v1, v2);
- case LUA_OPBAND: return intop(&, v1, v2);
- case LUA_OPBOR: return intop(|, v1, v2);
- case LUA_OPBXOR: return intop(^, v1, v2);
- case LUA_OPSHL: return luaV_shiftl(v1, v2);
- case LUA_OPSHR: return luaV_shiftr(v1, v2);
- case LUA_OPUNM: return intop(-, 0, v1);
- case LUA_OPBNOT: return intop(^, ~l_castS2U(0), v1);
- default: lua_assert(0); return 0;
- }
-}
-
-
-static lua_Number numarith (lua_State *L, int op, lua_Number v1,
- lua_Number v2) {
- switch (op) {
- case LUA_OPADD: return luai_numadd(L, v1, v2);
- case LUA_OPSUB: return luai_numsub(L, v1, v2);
- case LUA_OPMUL: return luai_nummul(L, v1, v2);
- case LUA_OPDIV: return luai_numdiv(L, v1, v2);
- case LUA_OPPOW: return luai_numpow(L, v1, v2);
- case LUA_OPIDIV: return luai_numidiv(L, v1, v2);
- case LUA_OPUNM: return luai_numunm(L, v1);
- case LUA_OPMOD: return luaV_modf(L, v1, v2);
- default: lua_assert(0); return 0;
- }
-}
-
-
-int luaO_rawarith (lua_State *L, int op, const TValue *p1, const TValue *p2,
- TValue *res) {
- switch (op) {
- case LUA_OPBAND: case LUA_OPBOR: case LUA_OPBXOR:
- case LUA_OPSHL: case LUA_OPSHR:
- case LUA_OPBNOT: { /* operate only on integers */
- lua_Integer i1; lua_Integer i2;
- if (tointegerns(p1, &i1) && tointegerns(p2, &i2)) {
- setivalue(res, intarith(L, op, i1, i2));
- return 1;
- }
- else return 0; /* fail */
- }
- case LUA_OPDIV: case LUA_OPPOW: { /* operate only on floats */
- lua_Number n1; lua_Number n2;
- if (tonumberns(p1, n1) && tonumberns(p2, n2)) {
- setfltvalue(res, numarith(L, op, n1, n2));
- return 1;
- }
- else return 0; /* fail */
- }
- default: { /* other operations */
- lua_Number n1; lua_Number n2;
- if (ttisinteger(p1) && ttisinteger(p2)) {
- setivalue(res, intarith(L, op, ivalue(p1), ivalue(p2)));
- return 1;
- }
- else if (tonumberns(p1, n1) && tonumberns(p2, n2)) {
- setfltvalue(res, numarith(L, op, n1, n2));
- return 1;
- }
- else return 0; /* fail */
- }
- }
-}
-
-
-void luaO_arith (lua_State *L, int op, const TValue *p1, const TValue *p2,
- StkId res) {
- if (!luaO_rawarith(L, op, p1, p2, s2v(res))) {
- /* could not perform raw operation; try metamethod */
- luaT_trybinTM(L, p1, p2, res, cast(TMS, (op - LUA_OPADD) + TM_ADD));
- }
-}
-
-
-lu_byte luaO_hexavalue (int c) {
- lua_assert(lisxdigit(c));
- if (lisdigit(c)) return cast_byte(c - '0');
- else return cast_byte((ltolower(c) - 'a') + 10);
-}
-
-
-static int isneg (const char **s) {
- if (**s == '-') { (*s)++; return 1; }
- else if (**s == '+') (*s)++;
- return 0;
-}
-
-
-
-/*
-** {==================================================================
-** Lua's implementation for 'lua_strx2number'
-** ===================================================================
-*/
-
-#if !defined(lua_strx2number)
-
-/* maximum number of significant digits to read (to avoid overflows
- even with single floats) */
-#define MAXSIGDIG 30
-
-/*
-** convert a hexadecimal numeric string to a number, following
-** C99 specification for 'strtod'
-*/
-static lua_Number lua_strx2number (const char *s, char **endptr) {
- int dot = lua_getlocaledecpoint();
- lua_Number r = l_mathop(0.0); /* result (accumulator) */
- int sigdig = 0; /* number of significant digits */
- int nosigdig = 0; /* number of non-significant digits */
- int e = 0; /* exponent correction */
- int neg; /* 1 if number is negative */
- int hasdot = 0; /* true after seen a dot */
- *endptr = cast_charp(s); /* nothing is valid yet */
- while (lisspace(cast_uchar(*s))) s++; /* skip initial spaces */
- neg = isneg(&s); /* check sign */
- if (!(*s == '0' && (*(s + 1) == 'x' || *(s + 1) == 'X'))) /* check '0x' */
- return l_mathop(0.0); /* invalid format (no '0x') */
- for (s += 2; ; s++) { /* skip '0x' and read numeral */
- if (*s == dot) {
- if (hasdot) break; /* second dot? stop loop */
- else hasdot = 1;
- }
- else if (lisxdigit(cast_uchar(*s))) {
- if (sigdig == 0 && *s == '0') /* non-significant digit (zero)? */
- nosigdig++;
- else if (++sigdig <= MAXSIGDIG) /* can read it without overflow? */
- r = (r * l_mathop(16.0)) + luaO_hexavalue(*s);
- else e++; /* too many digits; ignore, but still count for exponent */
- if (hasdot) e--; /* decimal digit? correct exponent */
- }
- else break; /* neither a dot nor a digit */
- }
- if (nosigdig + sigdig == 0) /* no digits? */
- return l_mathop(0.0); /* invalid format */
- *endptr = cast_charp(s); /* valid up to here */
- e *= 4; /* each digit multiplies/divides value by 2^4 */
- if (*s == 'p' || *s == 'P') { /* exponent part? */
- int exp1 = 0; /* exponent value */
- int neg1; /* exponent sign */
- s++; /* skip 'p' */
- neg1 = isneg(&s); /* sign */
- if (!lisdigit(cast_uchar(*s)))
- return l_mathop(0.0); /* invalid; must have at least one digit */
- while (lisdigit(cast_uchar(*s))) /* read exponent */
- exp1 = exp1 * 10 + *(s++) - '0';
- if (neg1) exp1 = -exp1;
- e += exp1;
- *endptr = cast_charp(s); /* valid up to here */
- }
- if (neg) r = -r;
- return l_mathop(ldexp)(r, e);
-}
-
-#endif
-/* }====================================================== */
-
-
-/* maximum length of a numeral to be converted to a number */
-#if !defined (L_MAXLENNUM)
-#define L_MAXLENNUM 200
-#endif
-
-/*
-** Convert string 's' to a Lua number (put in 'result'). Return NULL on
-** fail or the address of the ending '\0' on success. ('mode' == 'x')
-** means a hexadecimal numeral.
-*/
-static const char *l_str2dloc (const char *s, lua_Number *result, int mode) {
- char *endptr;
- *result = (mode == 'x') ? lua_strx2number(s, &endptr) /* try to convert */
- : lua_str2number(s, &endptr);
- if (endptr == s) return NULL; /* nothing recognized? */
- while (lisspace(cast_uchar(*endptr))) endptr++; /* skip trailing spaces */
- return (*endptr == '\0') ? endptr : NULL; /* OK iff no trailing chars */
-}
-
-
-/*
-** Convert string 's' to a Lua number (put in 'result') handling the
-** current locale.
-** This function accepts both the current locale or a dot as the radix
-** mark. If the conversion fails, it may mean number has a dot but
-** locale accepts something else. In that case, the code copies 's'
-** to a buffer (because 's' is read-only), changes the dot to the
-** current locale radix mark, and tries to convert again.
-** The variable 'mode' checks for special characters in the string:
-** - 'n' means 'inf' or 'nan' (which should be rejected)
-** - 'x' means a hexadecimal numeral
-** - '.' just optimizes the search for the common case (no special chars)
-*/
-static const char *l_str2d (const char *s, lua_Number *result) {
- const char *endptr;
- const char *pmode = strpbrk(s, ".xXnN"); /* look for special chars */
- int mode = pmode ? ltolower(cast_uchar(*pmode)) : 0;
- if (mode == 'n') /* reject 'inf' and 'nan' */
- return NULL;
- endptr = l_str2dloc(s, result, mode); /* try to convert */
- if (endptr == NULL) { /* failed? may be a different locale */
- char buff[L_MAXLENNUM + 1];
- const char *pdot = strchr(s, '.');
- if (pdot == NULL || strlen(s) > L_MAXLENNUM)
- return NULL; /* string too long or no dot; fail */
- strcpy(buff, s); /* copy string to buffer */
- buff[pdot - s] = lua_getlocaledecpoint(); /* correct decimal point */
- endptr = l_str2dloc(buff, result, mode); /* try again */
- if (endptr != NULL)
- endptr = s + (endptr - buff); /* make relative to 's' */
- }
- return endptr;
-}
-
-
-#define MAXBY10 cast(lua_Unsigned, LUA_MAXINTEGER / 10)
-#define MAXLASTD cast_int(LUA_MAXINTEGER % 10)
-
-static const char *l_str2int (const char *s, lua_Integer *result) {
- lua_Unsigned a = 0;
- int empty = 1;
- int neg;
- while (lisspace(cast_uchar(*s))) s++; /* skip initial spaces */
- neg = isneg(&s);
- if (s[0] == '0' &&
- (s[1] == 'x' || s[1] == 'X')) { /* hex? */
- s += 2; /* skip '0x' */
- for (; lisxdigit(cast_uchar(*s)); s++) {
- a = a * 16 + luaO_hexavalue(*s);
- empty = 0;
- }
- }
- else { /* decimal */
- for (; lisdigit(cast_uchar(*s)); s++) {
- int d = *s - '0';
- if (a >= MAXBY10 && (a > MAXBY10 || d > MAXLASTD + neg)) /* overflow? */
- return NULL; /* do not accept it (as integer) */
- a = a * 10 + cast_uint(d);
- empty = 0;
- }
- }
- while (lisspace(cast_uchar(*s))) s++; /* skip trailing spaces */
- if (empty || *s != '\0') return NULL; /* something wrong in the numeral */
- else {
- *result = l_castU2S((neg) ? 0u - a : a);
- return s;
- }
-}
-
-
-size_t luaO_str2num (const char *s, TValue *o) {
- lua_Integer i; lua_Number n;
- const char *e;
- if ((e = l_str2int(s, &i)) != NULL) { /* try as an integer */
- setivalue(o, i);
- }
- else if ((e = l_str2d(s, &n)) != NULL) { /* else try as a float */
- setfltvalue(o, n);
- }
- else
- return 0; /* conversion failed */
- return ct_diff2sz(e - s) + 1; /* success; return string size */
-}
-
-
-int luaO_utf8esc (char *buff, l_uint32 x) {
- int n = 1; /* number of bytes put in buffer (backwards) */
- lua_assert(x <= 0x7FFFFFFFu);
- if (x < 0x80) /* ASCII? */
- buff[UTF8BUFFSZ - 1] = cast_char(x);
- else { /* need continuation bytes */
- unsigned int mfb = 0x3f; /* maximum that fits in first byte */
- do { /* add continuation bytes */
- buff[UTF8BUFFSZ - (n++)] = cast_char(0x80 | (x & 0x3f));
- x >>= 6; /* remove added bits */
- mfb >>= 1; /* now there is one less bit available in first byte */
- } while (x > mfb); /* still needs continuation byte? */
- buff[UTF8BUFFSZ - n] = cast_char((~mfb << 1) | x); /* add first byte */
- }
- return n;
-}
-
-
-/*
-** The size of the buffer for the conversion of a number to a string
-** 'LUA_N2SBUFFSZ' must be enough to accommodate both LUA_INTEGER_FMT
-** and LUA_NUMBER_FMT. For a long long int, this is 19 digits plus a
-** sign and a final '\0', adding to 21. For a long double, it can go to
-** a sign, the dot, an exponent letter, an exponent sign, 4 exponent
-** digits, the final '\0', plus the significant digits, which are
-** approximately the *_DIG attribute.
-*/
-#if LUA_N2SBUFFSZ < (20 + l_floatatt(DIG))
-#error "invalid value for LUA_N2SBUFFSZ"
-#endif
-
-
-/*
-** Convert a float to a string, adding it to a buffer. First try with
-** a not too large number of digits, to avoid noise (for instance,
-** 1.1 going to "1.1000000000000001"). If that lose precision, so
-** that reading the result back gives a different number, then do the
-** conversion again with extra precision. Moreover, if the numeral looks
-** like an integer (without a decimal point or an exponent), add ".0" to
-** its end.
-*/
-static int tostringbuffFloat (lua_Number n, char *buff) {
- /* first conversion */
- int len = l_sprintf(buff, LUA_N2SBUFFSZ, LUA_NUMBER_FMT,
- (LUAI_UACNUMBER)n);
- lua_Number check = lua_str2number(buff, NULL); /* read it back */
- if (check != n) { /* not enough precision? */
- /* convert again with more precision */
- len = l_sprintf(buff, LUA_N2SBUFFSZ, LUA_NUMBER_FMT_N,
- (LUAI_UACNUMBER)n);
- }
- /* looks like an integer? */
- if (buff[strspn(buff, "-0123456789")] == '\0') {
- buff[len++] = lua_getlocaledecpoint();
- buff[len++] = '0'; /* adds '.0' to result */
- }
- return len;
-}
-
-
-/*
-** Convert a number object to a string, adding it to a buffer.
-*/
-unsigned luaO_tostringbuff (const TValue *obj, char *buff) {
- int len;
- lua_assert(ttisnumber(obj));
- if (ttisinteger(obj))
- len = lua_integer2str(buff, LUA_N2SBUFFSZ, ivalue(obj));
- else
- len = tostringbuffFloat(fltvalue(obj), buff);
- lua_assert(len < LUA_N2SBUFFSZ);
- return cast_uint(len);
-}
-
-
-/*
-** Convert a number object to a Lua string, replacing the value at 'obj'
-*/
-void luaO_tostring (lua_State *L, TValue *obj) {
- char buff[LUA_N2SBUFFSZ];
- unsigned len = luaO_tostringbuff(obj, buff);
- setsvalue(L, obj, luaS_newlstr(L, buff, len));
-}
-
-
-
-
-/*
-** {==================================================================
-** 'luaO_pushvfstring'
-** ===================================================================
-*/
-
-/*
-** Size for buffer space used by 'luaO_pushvfstring'. It should be
-** (LUA_IDSIZE + LUA_N2SBUFFSZ) + a minimal space for basic messages,
-** so that 'luaG_addinfo' can work directly on the static buffer.
-*/
-#define BUFVFS cast_uint(LUA_IDSIZE + LUA_N2SBUFFSZ + 95)
-
-/*
-** Buffer used by 'luaO_pushvfstring'. 'err' signals an error while
-** building result (memory error [1] or buffer overflow [2]).
-*/
-typedef struct BuffFS {
- lua_State *L;
- char *b;
- size_t buffsize;
- size_t blen; /* length of string in 'buff' */
- int err;
- char space[BUFVFS]; /* initial buffer */
-} BuffFS;
-
-
-static void initbuff (lua_State *L, BuffFS *buff) {
- buff->L = L;
- buff->b = buff->space;
- buff->buffsize = sizeof(buff->space);
- buff->blen = 0;
- buff->err = 0;
-}
-
-
-/*
-** Push final result from 'luaO_pushvfstring'. This function may raise
-** errors explicitly or through memory errors, so it must run protected.
-*/
-static void pushbuff (lua_State *L, void *ud) {
- BuffFS *buff = cast(BuffFS*, ud);
- switch (buff->err) {
- case 1: /* memory error */
- luaD_throw(L, LUA_ERRMEM);
- break;
- case 2: /* length overflow: Add "..." at the end of result */
- if (buff->buffsize - buff->blen < 3)
- strcpy(buff->b + buff->blen - 3, "..."); /* 'blen' must be > 3 */
- else { /* there is enough space left for the "..." */
- strcpy(buff->b + buff->blen, "...");
- buff->blen += 3;
- }
- /* FALLTHROUGH */
- default: { /* no errors, but it can raise one creating the new string */
- TString *ts = luaS_newlstr(L, buff->b, buff->blen);
- setsvalue2s(L, L->top.p, ts);
- L->top.p++;
- }
- }
-}
-
-
-static const char *clearbuff (BuffFS *buff) {
- lua_State *L = buff->L;
- const char *res;
- if (luaD_rawrunprotected(L, pushbuff, buff) != LUA_OK) /* errors? */
- res = NULL; /* error message is on the top of the stack */
- else
- res = getstr(tsvalue(s2v(L->top.p - 1)));
- if (buff->b != buff->space) /* using dynamic buffer? */
- luaM_freearray(L, buff->b, buff->buffsize); /* free it */
- return res;
-}
-
-
-static void addstr2buff (BuffFS *buff, const char *str, size_t slen) {
- size_t left = buff->buffsize - buff->blen; /* space left in the buffer */
- if (buff->err) /* do nothing else after an error */
- return;
- if (slen > left) { /* new string doesn't fit into current buffer? */
- if (slen > ((MAX_SIZE/2) - buff->blen)) { /* overflow? */
- memcpy(buff->b + buff->blen, str, left); /* copy what it can */
- buff->blen = buff->buffsize;
- buff->err = 2; /* doesn't add anything else */
- return;
- }
- else {
- size_t newsize = buff->buffsize + slen; /* limited to MAX_SIZE/2 */
- char *newb =
- (buff->b == buff->space) /* still using static space? */
- ? luaM_reallocvector(buff->L, NULL, 0, newsize, char)
- : luaM_reallocvector(buff->L, buff->b, buff->buffsize, newsize,
- char);
- if (newb == NULL) { /* allocation error? */
- buff->err = 1; /* signal a memory error */
- return;
- }
- if (buff->b == buff->space) /* new buffer (not reallocated)? */
- memcpy(newb, buff->b, buff->blen); /* copy previous content */
- buff->b = newb; /* set new (larger) buffer... */
- buff->buffsize = newsize; /* ...and its new size */
- }
- }
- memcpy(buff->b + buff->blen, str, slen); /* copy new content */
- buff->blen += slen;
-}
-
-
-/*
-** Add a numeral to the buffer.
-*/
-static void addnum2buff (BuffFS *buff, TValue *num) {
- char numbuff[LUA_N2SBUFFSZ];
- unsigned len = luaO_tostringbuff(num, numbuff);
- addstr2buff(buff, numbuff, len);
-}
-
-
-/*
-** this function handles only '%d', '%c', '%f', '%p', '%s', and '%%'
- conventional formats, plus Lua-specific '%I' and '%U'
-*/
-const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp) {
- BuffFS buff; /* holds last part of the result */
- const char *e; /* points to next '%' */
- initbuff(L, &buff);
- while ((e = strchr(fmt, '%')) != NULL) {
- addstr2buff(&buff, fmt, ct_diff2sz(e - fmt)); /* add 'fmt' up to '%' */
- switch (*(e + 1)) { /* conversion specifier */
- case 's': { /* zero-terminated string */
- const char *s = va_arg(argp, char *);
- if (s == NULL) s = "(null)";
- addstr2buff(&buff, s, strlen(s));
- break;
- }
- case 'c': { /* an 'int' as a character */
- char c = cast_char(va_arg(argp, int));
- addstr2buff(&buff, &c, sizeof(char));
- break;
- }
- case 'd': { /* an 'int' */
- TValue num;
- setivalue(&num, va_arg(argp, int));
- addnum2buff(&buff, &num);
- break;
- }
- case 'I': { /* a 'lua_Integer' */
- TValue num;
- setivalue(&num, cast_Integer(va_arg(argp, l_uacInt)));
- addnum2buff(&buff, &num);
- break;
- }
- case 'f': { /* a 'lua_Number' */
- TValue num;
- setfltvalue(&num, cast_num(va_arg(argp, l_uacNumber)));
- addnum2buff(&buff, &num);
- break;
- }
- case 'p': { /* a pointer */
- char bf[LUA_N2SBUFFSZ]; /* enough space for '%p' */
- void *p = va_arg(argp, void *);
- int len = lua_pointer2str(bf, LUA_N2SBUFFSZ, p);
- addstr2buff(&buff, bf, cast_uint(len));
- break;
- }
- case 'U': { /* an 'unsigned long' as a UTF-8 sequence */
- char bf[UTF8BUFFSZ];
- unsigned long arg = va_arg(argp, unsigned long);
- int len = luaO_utf8esc(bf, cast(l_uint32, arg));
- addstr2buff(&buff, bf + UTF8BUFFSZ - len, cast_uint(len));
- break;
- }
- case '%': {
- addstr2buff(&buff, "%", 1);
- break;
- }
- default: {
- addstr2buff(&buff, e, 2); /* keep unknown format in the result */
- break;
- }
- }
- fmt = e + 2; /* skip '%' and the specifier */
- }
- addstr2buff(&buff, fmt, strlen(fmt)); /* rest of 'fmt' */
- return clearbuff(&buff); /* empty buffer into a new string */
-}
-
-
-const char *luaO_pushfstring (lua_State *L, const char *fmt, ...) {
- const char *msg;
- va_list argp;
- va_start(argp, fmt);
- msg = luaO_pushvfstring(L, fmt, argp);
- va_end(argp);
- if (msg == NULL) /* error? */
- luaD_throw(L, LUA_ERRMEM);
- return msg;
-}
-
-/* }================================================================== */
-
-
-#define RETS "..."
-#define PRE "[string \""
-#define POS "\"]"
-
-#define addstr(a,b,l) ( memcpy(a,b,(l) * sizeof(char)), a += (l) )
-
-void luaO_chunkid (char *out, const char *source, size_t srclen) {
- size_t bufflen = LUA_IDSIZE; /* free space in buffer */
- if (*source == '=') { /* 'literal' source */
- if (srclen <= bufflen) /* small enough? */
- memcpy(out, source + 1, srclen * sizeof(char));
- else { /* truncate it */
- addstr(out, source + 1, bufflen - 1);
- *out = '\0';
- }
- }
- else if (*source == '@') { /* file name */
- if (srclen <= bufflen) /* small enough? */
- memcpy(out, source + 1, srclen * sizeof(char));
- else { /* add '...' before rest of name */
- addstr(out, RETS, LL(RETS));
- bufflen -= LL(RETS);
- memcpy(out, source + 1 + srclen - bufflen, bufflen * sizeof(char));
- }
- }
- else { /* string; format as [string "source"] */
- const char *nl = strchr(source, '\n'); /* find first new line (if any) */
- addstr(out, PRE, LL(PRE)); /* add prefix */
- bufflen -= LL(PRE RETS POS) + 1; /* save space for prefix+suffix+'\0' */
- if (srclen < bufflen && nl == NULL) { /* small one-line source? */
- addstr(out, source, srclen); /* keep it */
- }
- else {
- if (nl != NULL)
- srclen = ct_diff2sz(nl - source); /* stop at first newline */
- if (srclen > bufflen) srclen = bufflen;
- addstr(out, source, srclen);
- addstr(out, RETS, LL(RETS));
- }
- memcpy(out, POS, (LL(POS) + 1) * sizeof(char));
- }
-}
-
diff --git a/lobject.h b/lobject.h
deleted file mode 100644
index 156c942f01..0000000000
--- a/lobject.h
+++ /dev/null
@@ -1,864 +0,0 @@
-/*
-** $Id: lobject.h $
-** Type definitions for Lua objects
-** See Copyright Notice in lua.h
-*/
-
-
-#ifndef lobject_h
-#define lobject_h
-
-
-#include
-
-
-#include "llimits.h"
-#include "lua.h"
-
-
-/*
-** Extra types for collectable non-values
-*/
-#define LUA_TUPVAL LUA_NUMTYPES /* upvalues */
-#define LUA_TPROTO (LUA_NUMTYPES+1) /* function prototypes */
-#define LUA_TDEADKEY (LUA_NUMTYPES+2) /* removed keys in tables */
-
-
-
-/*
-** number of all possible types (including LUA_TNONE but excluding DEADKEY)
-*/
-#define LUA_TOTALTYPES (LUA_TPROTO + 2)
-
-
-/*
-** tags for Tagged Values have the following use of bits:
-** bits 0-3: actual tag (a LUA_T* constant)
-** bits 4-5: variant bits
-** bit 6: whether value is collectable
-*/
-
-/* add variant bits to a type */
-#define makevariant(t,v) ((t) | ((v) << 4))
-
-
-
-/*
-** Union of all Lua values
-*/
-typedef union Value {
- struct GCObject *gc; /* collectable objects */
- void *p; /* light userdata */
- lua_CFunction f; /* light C functions */
- lua_Integer i; /* integer numbers */
- lua_Number n; /* float numbers */
- /* not used, but may avoid warnings for uninitialized value */
- lu_byte ub;
-} Value;
-
-
-/*
-** Tagged Values. This is the basic representation of values in Lua:
-** an actual value plus a tag with its type.
-*/
-
-#define TValuefields Value value_; lu_byte tt_
-
-typedef struct TValue {
- TValuefields;
-} TValue;
-
-
-#define val_(o) ((o)->value_)
-#define valraw(o) (val_(o))
-
-
-/* raw type tag of a TValue */
-#define rawtt(o) ((o)->tt_)
-
-/* tag with no variants (bits 0-3) */
-#define novariant(t) ((t) & 0x0F)
-
-/* type tag of a TValue (bits 0-3 for tags + variant bits 4-5) */
-#define withvariant(t) ((t) & 0x3F)
-#define ttypetag(o) withvariant(rawtt(o))
-
-/* type of a TValue */
-#define ttype(o) (novariant(rawtt(o)))
-
-
-/* Macros to test type */
-#define checktag(o,t) (rawtt(o) == (t))
-#define checktype(o,t) (ttype(o) == (t))
-
-
-/* Macros for internal tests */
-
-/* collectable object has the same tag as the original value */
-#define righttt(obj) (ttypetag(obj) == gcvalue(obj)->tt)
-
-/*
-** Any value being manipulated by the program either is non
-** collectable, or the collectable object has the right tag
-** and it is not dead. The option 'L == NULL' allows other
-** macros using this one to be used where L is not available.
-*/
-#define checkliveness(L,obj) \
- ((void)L, lua_longassert(!iscollectable(obj) || \
- (righttt(obj) && (L == NULL || !isdead(G(L),gcvalue(obj))))))
-
-
-/* Macros to set values */
-
-/* set a value's tag */
-#define settt_(o,t) ((o)->tt_=(t))
-
-
-/* main macro to copy values (from 'obj2' to 'obj1') */
-#define setobj(L,obj1,obj2) \
- { TValue *io1=(obj1); const TValue *io2=(obj2); \
- io1->value_ = io2->value_; settt_(io1, io2->tt_); \
- checkliveness(L,io1); lua_assert(!isnonstrictnil(io1)); }
-
-/*
-** Different types of assignments, according to source and destination.
-** (They are mostly equal now, but may be different in the future.)
-*/
-
-/* from stack to stack */
-#define setobjs2s(L,o1,o2) setobj(L,s2v(o1),s2v(o2))
-/* to stack (not from same stack) */
-#define setobj2s(L,o1,o2) setobj(L,s2v(o1),o2)
-/* from table to same table */
-#define setobjt2t setobj
-/* to new object */
-#define setobj2n setobj
-/* to table */
-#define setobj2t setobj
-
-
-/*
-** Entries in a Lua stack. Field 'tbclist' forms a list of all
-** to-be-closed variables active in this stack. Dummy entries are
-** used when the distance between two tbc variables does not fit
-** in an unsigned short. They are represented by delta==0, and
-** their real delta is always the maximum value that fits in
-** that field.
-*/
-typedef union StackValue {
- TValue val;
- struct {
- TValuefields;
- unsigned short delta;
- } tbclist;
-} StackValue;
-
-
-/* index to stack elements */
-typedef StackValue *StkId;
-
-
-/*
-** When reallocating the stack, change all pointers to the stack into
-** proper offsets.
-*/
-typedef union {
- StkId p; /* actual pointer */
- ptrdiff_t offset; /* used while the stack is being reallocated */
-} StkIdRel;
-
-
-/* convert a 'StackValue' to a 'TValue' */
-#define s2v(o) (&(o)->val)
-
-
-
-/*
-** {==================================================================
-** Nil
-** ===================================================================
-*/
-
-/* Standard nil */
-#define LUA_VNIL makevariant(LUA_TNIL, 0)
-
-/* Empty slot (which might be different from a slot containing nil) */
-#define LUA_VEMPTY makevariant(LUA_TNIL, 1)
-
-/* Value returned for a key not found in a table (absent key) */
-#define LUA_VABSTKEY makevariant(LUA_TNIL, 2)
-
-/* Special variant to signal that a fast get is accessing a non-table */
-#define LUA_VNOTABLE makevariant(LUA_TNIL, 3)
-
-
-/* macro to test for (any kind of) nil */
-#define ttisnil(v) checktype((v), LUA_TNIL)
-
-/*
-** Macro to test the result of a table access. Formally, it should
-** distinguish between LUA_VEMPTY/LUA_VABSTKEY/LUA_VNOTABLE and
-** other tags. As currently nil is equivalent to LUA_VEMPTY, it is
-** simpler to just test whether the value is nil.
-*/
-#define tagisempty(tag) (novariant(tag) == LUA_TNIL)
-
-
-/* macro to test for a standard nil */
-#define ttisstrictnil(o) checktag((o), LUA_VNIL)
-
-
-#define setnilvalue(obj) settt_(obj, LUA_VNIL)
-
-
-#define isabstkey(v) checktag((v), LUA_VABSTKEY)
-
-
-/*
-** macro to detect non-standard nils (used only in assertions)
-*/
-#define isnonstrictnil(v) (ttisnil(v) && !ttisstrictnil(v))
-
-
-/*
-** By default, entries with any kind of nil are considered empty.
-** (In any definition, values associated with absent keys must also
-** be accepted as empty.)
-*/
-#define isempty(v) ttisnil(v)
-
-
-/* macro defining a value corresponding to an absent key */
-#define ABSTKEYCONSTANT {NULL}, LUA_VABSTKEY
-
-
-/* mark an entry as empty */
-#define setempty(v) settt_(v, LUA_VEMPTY)
-
-
-
-/* }================================================================== */
-
-
-/*
-** {==================================================================
-** Booleans
-** ===================================================================
-*/
-
-
-#define LUA_VFALSE makevariant(LUA_TBOOLEAN, 0)
-#define LUA_VTRUE makevariant(LUA_TBOOLEAN, 1)
-
-#define ttisboolean(o) checktype((o), LUA_TBOOLEAN)
-#define ttisfalse(o) checktag((o), LUA_VFALSE)
-#define ttistrue(o) checktag((o), LUA_VTRUE)
-
-
-#define l_isfalse(o) (ttisfalse(o) || ttisnil(o))
-#define tagisfalse(t) ((t) == LUA_VFALSE || novariant(t) == LUA_TNIL)
-
-
-
-#define setbfvalue(obj) settt_(obj, LUA_VFALSE)
-#define setbtvalue(obj) settt_(obj, LUA_VTRUE)
-
-/* }================================================================== */
-
-
-/*
-** {==================================================================
-** Threads
-** ===================================================================
-*/
-
-#define LUA_VTHREAD makevariant(LUA_TTHREAD, 0)
-
-#define ttisthread(o) checktag((o), ctb(LUA_VTHREAD))
-
-#define thvalue(o) check_exp(ttisthread(o), gco2th(val_(o).gc))
-
-#define setthvalue(L,obj,x) \
- { TValue *io = (obj); lua_State *x_ = (x); \
- val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_VTHREAD)); \
- checkliveness(L,io); }
-
-#define setthvalue2s(L,o,t) setthvalue(L,s2v(o),t)
-
-/* }================================================================== */
-
-
-/*
-** {==================================================================
-** Collectable Objects
-** ===================================================================
-*/
-
-/*
-** Common Header for all collectable objects (in macro form, to be
-** included in other objects)
-*/
-#define CommonHeader struct GCObject *next; lu_byte tt; lu_byte marked
-
-
-/* Common type for all collectable objects */
-typedef struct GCObject {
- CommonHeader;
-} GCObject;
-
-
-/* Bit mark for collectable types */
-#define BIT_ISCOLLECTABLE (1 << 6)
-
-#define iscollectable(o) (rawtt(o) & BIT_ISCOLLECTABLE)
-
-/* mark a tag as collectable */
-#define ctb(t) ((t) | BIT_ISCOLLECTABLE)
-
-#define gcvalue(o) check_exp(iscollectable(o), val_(o).gc)
-
-#define gcvalueraw(v) ((v).gc)
-
-#define setgcovalue(L,obj,x) \
- { TValue *io = (obj); GCObject *i_g=(x); \
- val_(io).gc = i_g; settt_(io, ctb(i_g->tt)); }
-
-/* }================================================================== */
-
-
-/*
-** {==================================================================
-** Numbers
-** ===================================================================
-*/
-
-/* Variant tags for numbers */
-#define LUA_VNUMINT makevariant(LUA_TNUMBER, 0) /* integer numbers */
-#define LUA_VNUMFLT makevariant(LUA_TNUMBER, 1) /* float numbers */
-
-#define ttisnumber(o) checktype((o), LUA_TNUMBER)
-#define ttisfloat(o) checktag((o), LUA_VNUMFLT)
-#define ttisinteger(o) checktag((o), LUA_VNUMINT)
-
-#define nvalue(o) check_exp(ttisnumber(o), \
- (ttisinteger(o) ? cast_num(ivalue(o)) : fltvalue(o)))
-#define fltvalue(o) check_exp(ttisfloat(o), val_(o).n)
-#define ivalue(o) check_exp(ttisinteger(o), val_(o).i)
-
-#define fltvalueraw(v) ((v).n)
-#define ivalueraw(v) ((v).i)
-
-#define setfltvalue(obj,x) \
- { TValue *io=(obj); val_(io).n=(x); settt_(io, LUA_VNUMFLT); }
-
-#define chgfltvalue(obj,x) \
- { TValue *io=(obj); lua_assert(ttisfloat(io)); val_(io).n=(x); }
-
-#define setivalue(obj,x) \
- { TValue *io=(obj); val_(io).i=(x); settt_(io, LUA_VNUMINT); }
-
-#define chgivalue(obj,x) \
- { TValue *io=(obj); lua_assert(ttisinteger(io)); val_(io).i=(x); }
-
-/* }================================================================== */
-
-
-/*
-** {==================================================================
-** Strings
-** ===================================================================
-*/
-
-/* Variant tags for strings */
-#define LUA_VSHRSTR makevariant(LUA_TSTRING, 0) /* short strings */
-#define LUA_VLNGSTR makevariant(LUA_TSTRING, 1) /* long strings */
-
-#define ttisstring(o) checktype((o), LUA_TSTRING)
-#define ttisshrstring(o) checktag((o), ctb(LUA_VSHRSTR))
-#define ttislngstring(o) checktag((o), ctb(LUA_VLNGSTR))
-
-#define tsvalueraw(v) (gco2ts((v).gc))
-
-#define tsvalue(o) check_exp(ttisstring(o), gco2ts(val_(o).gc))
-
-#define setsvalue(L,obj,x) \
- { TValue *io = (obj); TString *x_ = (x); \
- val_(io).gc = obj2gco(x_); settt_(io, ctb(x_->tt)); \
- checkliveness(L,io); }
-
-/* set a string to the stack */
-#define setsvalue2s(L,o,s) setsvalue(L,s2v(o),s)
-
-/* set a string to a new object */
-#define setsvalue2n setsvalue
-
-
-/* Kinds of long strings (stored in 'shrlen') */
-#define LSTRREG -1 /* regular long string */
-#define LSTRFIX -2 /* fixed external long string */
-#define LSTRMEM -3 /* external long string with deallocation */
-
-
-/*
-** Header for a string value.
-*/
-typedef struct TString {
- CommonHeader;
- lu_byte extra; /* reserved words for short strings; "has hash" for longs */
- ls_byte shrlen; /* length for short strings, negative for long strings */
- unsigned int hash;
- union {
- size_t lnglen; /* length for long strings */
- struct TString *hnext; /* linked list for hash table */
- } u;
- char *contents; /* pointer to content in long strings */
- lua_Alloc falloc; /* deallocation function for external strings */
- void *ud; /* user data for external strings */
-} TString;
-
-
-#define strisshr(ts) ((ts)->shrlen >= 0)
-#define isextstr(ts) (ttislngstring(ts) && tsvalue(ts)->shrlen != LSTRREG)
-
-
-/*
-** Get the actual string (array of bytes) from a 'TString'. (Generic
-** version and specialized versions for long and short strings.)
-*/
-#define rawgetshrstr(ts) (cast_charp(&(ts)->contents))
-#define getshrstr(ts) check_exp(strisshr(ts), rawgetshrstr(ts))
-#define getlngstr(ts) check_exp(!strisshr(ts), (ts)->contents)
-#define getstr(ts) (strisshr(ts) ? rawgetshrstr(ts) : (ts)->contents)
-
-
-/* get string length from 'TString *ts' */
-#define tsslen(ts) \
- (strisshr(ts) ? cast_sizet((ts)->shrlen) : (ts)->u.lnglen)
-
-/*
-** Get string and length */
-#define getlstr(ts, len) \
- (strisshr(ts) \
- ? (cast_void((len) = cast_sizet((ts)->shrlen)), rawgetshrstr(ts)) \
- : (cast_void((len) = (ts)->u.lnglen), (ts)->contents))
-
-/* }================================================================== */
-
-
-/*
-** {==================================================================
-** Userdata
-** ===================================================================
-*/
-
-
-/*
-** Light userdata should be a variant of userdata, but for compatibility
-** reasons they are also different types.
-*/
-#define LUA_VLIGHTUSERDATA makevariant(LUA_TLIGHTUSERDATA, 0)
-
-#define LUA_VUSERDATA makevariant(LUA_TUSERDATA, 0)
-
-#define ttislightuserdata(o) checktag((o), LUA_VLIGHTUSERDATA)
-#define ttisfulluserdata(o) checktag((o), ctb(LUA_VUSERDATA))
-
-#define pvalue(o) check_exp(ttislightuserdata(o), val_(o).p)
-#define uvalue(o) check_exp(ttisfulluserdata(o), gco2u(val_(o).gc))
-
-#define pvalueraw(v) ((v).p)
-
-#define setpvalue(obj,x) \
- { TValue *io=(obj); val_(io).p=(x); settt_(io, LUA_VLIGHTUSERDATA); }
-
-#define setuvalue(L,obj,x) \
- { TValue *io = (obj); Udata *x_ = (x); \
- val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_VUSERDATA)); \
- checkliveness(L,io); }
-
-
-/* Ensures that addresses after this type are always fully aligned. */
-typedef union UValue {
- TValue uv;
- LUAI_MAXALIGN; /* ensures maximum alignment for udata bytes */
-} UValue;
-
-
-/*
-** Header for userdata with user values;
-** memory area follows the end of this structure.
-*/
-typedef struct Udata {
- CommonHeader;
- unsigned short nuvalue; /* number of user values */
- size_t len; /* number of bytes */
- struct Table *metatable;
- GCObject *gclist;
- UValue uv[1]; /* user values */
-} Udata;
-
-
-/*
-** Header for userdata with no user values. These userdata do not need
-** to be gray during GC, and therefore do not need a 'gclist' field.
-** To simplify, the code always use 'Udata' for both kinds of userdata,
-** making sure it never accesses 'gclist' on userdata with no user values.
-** This structure here is used only to compute the correct size for
-** this representation. (The 'bindata' field in its end ensures correct
-** alignment for binary data following this header.)
-*/
-typedef struct Udata0 {
- CommonHeader;
- unsigned short nuvalue; /* number of user values */
- size_t len; /* number of bytes */
- struct Table *metatable;
- union {LUAI_MAXALIGN;} bindata;
-} Udata0;
-
-
-/* compute the offset of the memory area of a userdata */
-#define udatamemoffset(nuv) \
- ((nuv) == 0 ? offsetof(Udata0, bindata) \
- : offsetof(Udata, uv) + (sizeof(UValue) * (nuv)))
-
-/* get the address of the memory block inside 'Udata' */
-#define getudatamem(u) (cast_charp(u) + udatamemoffset((u)->nuvalue))
-
-/* compute the size of a userdata */
-#define sizeudata(nuv,nb) (udatamemoffset(nuv) + (nb))
-
-/* }================================================================== */
-
-
-/*
-** {==================================================================
-** Prototypes
-** ===================================================================
-*/
-
-#define LUA_VPROTO makevariant(LUA_TPROTO, 0)
-
-
-typedef l_uint32 Instruction;
-
-
-/*
-** Description of an upvalue for function prototypes
-*/
-typedef struct Upvaldesc {
- TString *name; /* upvalue name (for debug information) */
- lu_byte instack; /* whether it is in stack (register) */
- lu_byte idx; /* index of upvalue (in stack or in outer function's list) */
- lu_byte kind; /* kind of corresponding variable */
-} Upvaldesc;
-
-
-/*
-** Description of a local variable for function prototypes
-** (used for debug information)
-*/
-typedef struct LocVar {
- TString *varname;
- int startpc; /* first point where variable is active */
- int endpc; /* first point where variable is dead */
-} LocVar;
-
-
-/*
-** Associates the absolute line source for a given instruction ('pc').
-** The array 'lineinfo' gives, for each instruction, the difference in
-** lines from the previous instruction. When that difference does not
-** fit into a byte, Lua saves the absolute line for that instruction.
-** (Lua also saves the absolute line periodically, to speed up the
-** computation of a line number: we can use binary search in the
-** absolute-line array, but we must traverse the 'lineinfo' array
-** linearly to compute a line.)
-*/
-typedef struct AbsLineInfo {
- int pc;
- int line;
-} AbsLineInfo;
-
-
-/*
-** Flags in Prototypes
-*/
-#define PF_VAHID 1 /* function has hidden vararg arguments */
-#define PF_VATAB 2 /* function has vararg table */
-#define PF_FIXED 4 /* prototype has parts in fixed memory */
-
-/* a vararg function either has hidden args. or a vararg table */
-#define isvararg(p) ((p)->flag & (PF_VAHID | PF_VATAB))
-
-/*
-** mark that a function needs a vararg table. (The flag PF_VAHID will
-** be cleared later.)
-*/
-#define needvatab(p) ((p)->flag |= PF_VATAB)
-
-/*
-** Function Prototypes
-*/
-typedef struct Proto {
- CommonHeader;
- lu_byte numparams; /* number of fixed (named) parameters */
- lu_byte flag;
- lu_byte maxstacksize; /* number of registers needed by this function */
- int sizeupvalues; /* size of 'upvalues' */
- int sizek; /* size of 'k' */
- int sizecode;
- int sizelineinfo;
- int sizep; /* size of 'p' */
- int sizelocvars;
- int sizeabslineinfo; /* size of 'abslineinfo' */
- int linedefined; /* debug information */
- int lastlinedefined; /* debug information */
- TValue *k; /* constants used by the function */
- Instruction *code; /* opcodes */
- struct Proto **p; /* functions defined inside the function */
- Upvaldesc *upvalues; /* upvalue information */
- ls_byte *lineinfo; /* information about source lines (debug information) */
- AbsLineInfo *abslineinfo; /* idem */
- LocVar *locvars; /* information about local variables (debug information) */
- TString *source; /* used for debug information */
- GCObject *gclist;
-} Proto;
-
-/* }================================================================== */
-
-
-/*
-** {==================================================================
-** Functions
-** ===================================================================
-*/
-
-#define LUA_VUPVAL makevariant(LUA_TUPVAL, 0)
-
-
-/* Variant tags for functions */
-#define LUA_VLCL makevariant(LUA_TFUNCTION, 0) /* Lua closure */
-#define LUA_VLCF makevariant(LUA_TFUNCTION, 1) /* light C function */
-#define LUA_VCCL makevariant(LUA_TFUNCTION, 2) /* C closure */
-
-#define ttisfunction(o) checktype(o, LUA_TFUNCTION)
-#define ttisLclosure(o) checktag((o), ctb(LUA_VLCL))
-#define ttislcf(o) checktag((o), LUA_VLCF)
-#define ttisCclosure(o) checktag((o), ctb(LUA_VCCL))
-#define ttisclosure(o) (ttisLclosure(o) || ttisCclosure(o))
-
-
-#define isLfunction(o) ttisLclosure(o)
-
-#define clvalue(o) check_exp(ttisclosure(o), gco2cl(val_(o).gc))
-#define clLvalue(o) check_exp(ttisLclosure(o), gco2lcl(val_(o).gc))
-#define fvalue(o) check_exp(ttislcf(o), val_(o).f)
-#define clCvalue(o) check_exp(ttisCclosure(o), gco2ccl(val_(o).gc))
-
-#define fvalueraw(v) ((v).f)
-
-#define setclLvalue(L,obj,x) \
- { TValue *io = (obj); LClosure *x_ = (x); \
- val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_VLCL)); \
- checkliveness(L,io); }
-
-#define setclLvalue2s(L,o,cl) setclLvalue(L,s2v(o),cl)
-
-#define setfvalue(obj,x) \
- { TValue *io=(obj); val_(io).f=(x); settt_(io, LUA_VLCF); }
-
-#define setclCvalue(L,obj,x) \
- { TValue *io = (obj); CClosure *x_ = (x); \
- val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_VCCL)); \
- checkliveness(L,io); }
-
-
-/*
-** Upvalues for Lua closures
-*/
-typedef struct UpVal {
- CommonHeader;
- union {
- TValue *p; /* points to stack or to its own value */
- ptrdiff_t offset; /* used while the stack is being reallocated */
- } v;
- union {
- struct { /* (when open) */
- struct UpVal *next; /* linked list */
- struct UpVal **previous;
- } open;
- TValue value; /* the value (when closed) */
- } u;
-} UpVal;
-
-
-
-#define ClosureHeader \
- CommonHeader; lu_byte nupvalues; GCObject *gclist
-
-typedef struct CClosure {
- ClosureHeader;
- lua_CFunction f;
- TValue upvalue[1]; /* list of upvalues */
-} CClosure;
-
-
-typedef struct LClosure {
- ClosureHeader;
- struct Proto *p;
- UpVal *upvals[1]; /* list of upvalues */
-} LClosure;
-
-
-typedef union Closure {
- CClosure c;
- LClosure l;
-} Closure;
-
-
-#define getproto(o) (clLvalue(o)->p)
-
-/* }================================================================== */
-
-
-/*
-** {==================================================================
-** Tables
-** ===================================================================
-*/
-
-#define LUA_VTABLE makevariant(LUA_TTABLE, 0)
-
-#define ttistable(o) checktag((o), ctb(LUA_VTABLE))
-
-#define hvalue(o) check_exp(ttistable(o), gco2t(val_(o).gc))
-
-#define sethvalue(L,obj,x) \
- { TValue *io = (obj); Table *x_ = (x); \
- val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_VTABLE)); \
- checkliveness(L,io); }
-
-#define sethvalue2s(L,o,h) sethvalue(L,s2v(o),h)
-
-
-/*
-** Nodes for Hash tables: A pack of two TValue's (key-value pairs)
-** plus a 'next' field to link colliding entries. The distribution
-** of the key's fields ('key_tt' and 'key_val') not forming a proper
-** 'TValue' allows for a smaller size for 'Node' both in 4-byte
-** and 8-byte alignments.
-*/
-typedef union Node {
- struct NodeKey {
- TValuefields; /* fields for value */
- lu_byte key_tt; /* key type */
- int next; /* for chaining */
- Value key_val; /* key value */
- } u;
- TValue i_val; /* direct access to node's value as a proper 'TValue' */
-} Node;
-
-
-/* copy a value into a key */
-#define setnodekey(node,obj) \
- { Node *n_=(node); const TValue *io_=(obj); \
- n_->u.key_val = io_->value_; n_->u.key_tt = io_->tt_; }
-
-
-/* copy a value from a key */
-#define getnodekey(L,obj,node) \
- { TValue *io_=(obj); const Node *n_=(node); \
- io_->value_ = n_->u.key_val; io_->tt_ = n_->u.key_tt; \
- checkliveness(L,io_); }
-
-
-
-typedef struct Table {
- CommonHeader;
- lu_byte flags; /* 1<
u.key_tt)
-#define keyval(node) ((node)->u.key_val)
-
-#define keyisnil(node) (keytt(node) == LUA_TNIL)
-#define keyisinteger(node) (keytt(node) == LUA_VNUMINT)
-#define keyival(node) (keyval(node).i)
-#define keyisshrstr(node) (keytt(node) == ctb(LUA_VSHRSTR))
-#define keystrval(node) (gco2ts(keyval(node).gc))
-
-#define setnilkey(node) (keytt(node) = LUA_TNIL)
-
-#define keyiscollectable(n) (keytt(n) & BIT_ISCOLLECTABLE)
-
-#define gckey(n) (keyval(n).gc)
-#define gckeyN(n) (keyiscollectable(n) ? gckey(n) : NULL)
-
-
-/*
-** Dead keys in tables have the tag DEADKEY but keep their original
-** gcvalue. This distinguishes them from regular keys but allows them to
-** be found when searched in a special way. ('next' needs that to find
-** keys removed from a table during a traversal.)
-*/
-#define setdeadkey(node) (keytt(node) = LUA_TDEADKEY)
-#define keyisdead(node) (keytt(node) == LUA_TDEADKEY)
-
-/* }================================================================== */
-
-
-
-/*
-** 'module' operation for hashing (size is always a power of 2)
-*/
-#define lmod(s,size) \
- (check_exp((size&(size-1))==0, (cast_uint(s) & cast_uint((size)-1))))
-
-
-#define twoto(x) (1u<<(x))
-#define sizenode(t) (twoto((t)->lsizenode))
-
-
-/* size of buffer for 'luaO_utf8esc' function */
-#define UTF8BUFFSZ 8
-
-
-/* macro to call 'luaO_pushvfstring' correctly */
-#define pushvfstring(L, argp, fmt, msg) \
- { va_start(argp, fmt); \
- msg = luaO_pushvfstring(L, fmt, argp); \
- va_end(argp); \
- if (msg == NULL) luaD_throw(L, LUA_ERRMEM); /* only after 'va_end' */ }
-
-
-LUAI_FUNC int luaO_utf8esc (char *buff, l_uint32 x);
-LUAI_FUNC lu_byte luaO_ceillog2 (unsigned int x);
-LUAI_FUNC lu_byte luaO_codeparam (unsigned int p);
-LUAI_FUNC l_mem luaO_applyparam (lu_byte p, l_mem x);
-
-LUAI_FUNC int luaO_rawarith (lua_State *L, int op, const TValue *p1,
- const TValue *p2, TValue *res);
-LUAI_FUNC void luaO_arith (lua_State *L, int op, const TValue *p1,
- const TValue *p2, StkId res);
-LUAI_FUNC size_t luaO_str2num (const char *s, TValue *o);
-LUAI_FUNC unsigned luaO_tostringbuff (const TValue *obj, char *buff);
-LUAI_FUNC lu_byte luaO_hexavalue (int c);
-LUAI_FUNC void luaO_tostring (lua_State *L, TValue *obj);
-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, size_t srclen);
-
-
-#endif
-
diff --git a/lopcodes.c b/lopcodes.c
deleted file mode 100644
index c4828bfc02..0000000000
--- a/lopcodes.c
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
-** $Id: lopcodes.c $
-** Opcodes for Lua virtual machine
-** See Copyright Notice in lua.h
-*/
-
-#define lopcodes_c
-#define LUA_CORE
-
-#include "lprefix.h"
-
-
-#include "lopcodes.h"
-
-
-#define opmode(mm,ot,it,t,a,m) \
- (((mm) << 7) | ((ot) << 6) | ((it) << 5) | ((t) << 4) | ((a) << 3) | (m))
-
-
-/* ORDER OP */
-
-LUAI_DDEF const lu_byte luaP_opmodes[NUM_OPCODES] = {
-/* MM OT IT T A mode opcode */
- opmode(0, 0, 0, 0, 1, iABC) /* OP_MOVE */
- ,opmode(0, 0, 0, 0, 1, iAsBx) /* OP_LOADI */
- ,opmode(0, 0, 0, 0, 1, iAsBx) /* OP_LOADF */
- ,opmode(0, 0, 0, 0, 1, iABx) /* OP_LOADK */
- ,opmode(0, 0, 0, 0, 1, iABx) /* OP_LOADKX */
- ,opmode(0, 0, 0, 0, 1, iABC) /* OP_LOADFALSE */
- ,opmode(0, 0, 0, 0, 1, iABC) /* OP_LFALSESKIP */
- ,opmode(0, 0, 0, 0, 1, iABC) /* OP_LOADTRUE */
- ,opmode(0, 0, 0, 0, 1, iABC) /* OP_LOADNIL */
- ,opmode(0, 0, 0, 0, 1, iABC) /* OP_GETUPVAL */
- ,opmode(0, 0, 0, 0, 0, iABC) /* OP_SETUPVAL */
- ,opmode(0, 0, 0, 0, 1, iABC) /* OP_GETTABUP */
- ,opmode(0, 0, 0, 0, 1, iABC) /* OP_GETTABLE */
- ,opmode(0, 0, 0, 0, 1, iABC) /* OP_GETI */
- ,opmode(0, 0, 0, 0, 1, iABC) /* OP_GETFIELD */
- ,opmode(0, 0, 0, 0, 0, iABC) /* OP_SETTABUP */
- ,opmode(0, 0, 0, 0, 0, iABC) /* OP_SETTABLE */
- ,opmode(0, 0, 0, 0, 0, iABC) /* OP_SETI */
- ,opmode(0, 0, 0, 0, 0, iABC) /* OP_SETFIELD */
- ,opmode(0, 0, 0, 0, 1, ivABC) /* OP_NEWTABLE */
- ,opmode(0, 0, 0, 0, 1, iABC) /* OP_SELF */
- ,opmode(0, 0, 0, 0, 1, iABC) /* OP_ADDI */
- ,opmode(0, 0, 0, 0, 1, iABC) /* OP_ADDK */
- ,opmode(0, 0, 0, 0, 1, iABC) /* OP_SUBK */
- ,opmode(0, 0, 0, 0, 1, iABC) /* OP_MULK */
- ,opmode(0, 0, 0, 0, 1, iABC) /* OP_MODK */
- ,opmode(0, 0, 0, 0, 1, iABC) /* OP_POWK */
- ,opmode(0, 0, 0, 0, 1, iABC) /* OP_DIVK */
- ,opmode(0, 0, 0, 0, 1, iABC) /* OP_IDIVK */
- ,opmode(0, 0, 0, 0, 1, iABC) /* OP_BANDK */
- ,opmode(0, 0, 0, 0, 1, iABC) /* OP_BORK */
- ,opmode(0, 0, 0, 0, 1, iABC) /* OP_BXORK */
- ,opmode(0, 0, 0, 0, 1, iABC) /* OP_SHLI */
- ,opmode(0, 0, 0, 0, 1, iABC) /* OP_SHRI */
- ,opmode(0, 0, 0, 0, 1, iABC) /* OP_ADD */
- ,opmode(0, 0, 0, 0, 1, iABC) /* OP_SUB */
- ,opmode(0, 0, 0, 0, 1, iABC) /* OP_MUL */
- ,opmode(0, 0, 0, 0, 1, iABC) /* OP_MOD */
- ,opmode(0, 0, 0, 0, 1, iABC) /* OP_POW */
- ,opmode(0, 0, 0, 0, 1, iABC) /* OP_DIV */
- ,opmode(0, 0, 0, 0, 1, iABC) /* OP_IDIV */
- ,opmode(0, 0, 0, 0, 1, iABC) /* OP_BAND */
- ,opmode(0, 0, 0, 0, 1, iABC) /* OP_BOR */
- ,opmode(0, 0, 0, 0, 1, iABC) /* OP_BXOR */
- ,opmode(0, 0, 0, 0, 1, iABC) /* OP_SHL */
- ,opmode(0, 0, 0, 0, 1, iABC) /* OP_SHR */
- ,opmode(1, 0, 0, 0, 0, iABC) /* OP_MMBIN */
- ,opmode(1, 0, 0, 0, 0, iABC) /* OP_MMBINI */
- ,opmode(1, 0, 0, 0, 0, iABC) /* OP_MMBINK */
- ,opmode(0, 0, 0, 0, 1, iABC) /* OP_UNM */
- ,opmode(0, 0, 0, 0, 1, iABC) /* OP_BNOT */
- ,opmode(0, 0, 0, 0, 1, iABC) /* OP_NOT */
- ,opmode(0, 0, 0, 0, 1, iABC) /* OP_LEN */
- ,opmode(0, 0, 0, 0, 1, iABC) /* OP_CONCAT */
- ,opmode(0, 0, 0, 0, 0, iABC) /* OP_CLOSE */
- ,opmode(0, 0, 0, 0, 0, iABC) /* OP_TBC */
- ,opmode(0, 0, 0, 0, 0, isJ) /* OP_JMP */
- ,opmode(0, 0, 0, 1, 0, iABC) /* OP_EQ */
- ,opmode(0, 0, 0, 1, 0, iABC) /* OP_LT */
- ,opmode(0, 0, 0, 1, 0, iABC) /* OP_LE */
- ,opmode(0, 0, 0, 1, 0, iABC) /* OP_EQK */
- ,opmode(0, 0, 0, 1, 0, iABC) /* OP_EQI */
- ,opmode(0, 0, 0, 1, 0, iABC) /* OP_LTI */
- ,opmode(0, 0, 0, 1, 0, iABC) /* OP_LEI */
- ,opmode(0, 0, 0, 1, 0, iABC) /* OP_GTI */
- ,opmode(0, 0, 0, 1, 0, iABC) /* OP_GEI */
- ,opmode(0, 0, 0, 1, 0, iABC) /* OP_TEST */
- ,opmode(0, 0, 0, 1, 1, iABC) /* OP_TESTSET */
- ,opmode(0, 1, 1, 0, 1, iABC) /* OP_CALL */
- ,opmode(0, 1, 1, 0, 1, iABC) /* OP_TAILCALL */
- ,opmode(0, 0, 1, 0, 0, iABC) /* OP_RETURN */
- ,opmode(0, 0, 0, 0, 0, iABC) /* OP_RETURN0 */
- ,opmode(0, 0, 0, 0, 0, iABC) /* OP_RETURN1 */
- ,opmode(0, 0, 0, 0, 1, iABx) /* OP_FORLOOP */
- ,opmode(0, 0, 0, 0, 1, iABx) /* OP_FORPREP */
- ,opmode(0, 0, 0, 0, 0, iABx) /* OP_TFORPREP */
- ,opmode(0, 0, 0, 0, 0, iABC) /* OP_TFORCALL */
- ,opmode(0, 0, 0, 0, 1, iABx) /* OP_TFORLOOP */
- ,opmode(0, 0, 1, 0, 0, ivABC) /* OP_SETLIST */
- ,opmode(0, 0, 0, 0, 1, iABx) /* OP_CLOSURE */
- ,opmode(0, 1, 0, 0, 1, iABC) /* OP_VARARG */
- ,opmode(0, 0, 0, 0, 1, iABC) /* OP_GETVARG */
- ,opmode(0, 0, 0, 0, 0, iABx) /* OP_ERRNNIL */
- ,opmode(0, 0, 1, 0, 0, iABC) /* OP_VARARGPREP */
- ,opmode(0, 0, 0, 0, 0, iAx) /* OP_EXTRAARG */
-};
-
-
-
-/*
-** Check whether instruction sets top for next instruction, that is,
-** it results in multiple values.
-*/
-int luaP_isOT (Instruction i) {
- OpCode op = GET_OPCODE(i);
- switch (op) {
- case OP_TAILCALL: return 1;
- default:
- return testOTMode(op) && GETARG_C(i) == 0;
- }
-}
-
-
-/*
-** Check whether instruction uses top from previous instruction, that is,
-** it accepts multiple results.
-*/
-int luaP_isIT (Instruction i) {
- OpCode op = GET_OPCODE(i);
- switch (op) {
- case OP_SETLIST:
- return testITMode(GET_OPCODE(i)) && GETARG_vB(i) == 0;
- default:
- return testITMode(GET_OPCODE(i)) && GETARG_B(i) == 0;
- }
-}
-
diff --git a/lopcodes.h b/lopcodes.h
deleted file mode 100644
index b6bd182ea2..0000000000
--- a/lopcodes.h
+++ /dev/null
@@ -1,439 +0,0 @@
-/*
-** $Id: lopcodes.h $
-** Opcodes for Lua virtual machine
-** See Copyright Notice in lua.h
-*/
-
-#ifndef lopcodes_h
-#define lopcodes_h
-
-#include "llimits.h"
-#include "lobject.h"
-
-
-/*===========================================================================
- We assume that instructions are unsigned 32-bit integers.
- All instructions have an opcode in the first 7 bits.
- Instructions can have the following formats:
-
- 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0
- 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
-iABC C(8) | B(8) |k| A(8) | Op(7) |
-ivABC vC(10) | vB(6) |k| A(8) | Op(7) |
-iABx Bx(17) | A(8) | Op(7) |
-iAsBx sBx (signed)(17) | A(8) | Op(7) |
-iAx Ax(25) | Op(7) |
-isJ sJ (signed)(25) | Op(7) |
-
- ('v' stands for "variant", 's' for "signed", 'x' for "extended".)
- A signed argument is represented in excess K: The represented value is
- the written unsigned value minus K, where K is half (rounded down) the
- maximum value for the corresponding unsigned argument.
-===========================================================================*/
-
-
-/* basic instruction formats */
-enum OpMode {iABC, ivABC, iABx, iAsBx, iAx, isJ};
-
-
-/*
-** size and position of opcode arguments.
-*/
-#define SIZE_C 8
-#define SIZE_vC 10
-#define SIZE_B 8
-#define SIZE_vB 6
-#define SIZE_Bx (SIZE_C + SIZE_B + 1)
-#define SIZE_A 8
-#define SIZE_Ax (SIZE_Bx + SIZE_A)
-#define SIZE_sJ (SIZE_Bx + SIZE_A)
-
-#define SIZE_OP 7
-
-#define POS_OP 0
-
-#define POS_A (POS_OP + SIZE_OP)
-#define POS_k (POS_A + SIZE_A)
-#define POS_B (POS_k + 1)
-#define POS_vB (POS_k + 1)
-#define POS_C (POS_B + SIZE_B)
-#define POS_vC (POS_vB + SIZE_vB)
-
-#define POS_Bx POS_k
-
-#define POS_Ax POS_A
-
-#define POS_sJ POS_A
-
-
-/*
-** limits for opcode arguments.
-** we use (signed) 'int' to manipulate most arguments,
-** so they must fit in ints.
-*/
-
-/*
-** Check whether type 'int' has at least 'b' + 1 bits.
-** 'b' < 32; +1 for the sign bit.
-*/
-#define L_INTHASBITS(b) ((UINT_MAX >> (b)) >= 1)
-
-
-#if L_INTHASBITS(SIZE_Bx)
-#define MAXARG_Bx ((1<>1) /* 'sBx' is signed */
-
-
-#if L_INTHASBITS(SIZE_Ax)
-#define MAXARG_Ax ((1<> 1)
-
-
-#define MAXARG_A ((1<> 1)
-
-#define int2sC(i) ((i) + OFFSET_sC)
-#define sC2int(i) ((i) - OFFSET_sC)
-
-
-/* creates a mask with 'n' 1 bits at position 'p' */
-#define MASK1(n,p) ((~((~(Instruction)0)<<(n)))<<(p))
-
-/* creates a mask with 'n' 0 bits at position 'p' */
-#define MASK0(n,p) (~MASK1(n,p))
-
-/*
-** the following macros help to manipulate instructions
-*/
-
-#define GET_OPCODE(i) (cast(OpCode, ((i)>>POS_OP) & MASK1(SIZE_OP,0)))
-#define SET_OPCODE(i,o) ((i) = (((i)&MASK0(SIZE_OP,POS_OP)) | \
- ((cast_Inst(o)<>(pos)) & MASK1(size,0)))
-#define setarg(i,v,pos,size) ((i) = (((i)&MASK0(size,pos)) | \
- ((cast_Inst(v)<> sC */
-
-OP_ADD,/* A B C R[A] := R[B] + R[C] */
-OP_SUB,/* A B C R[A] := R[B] - R[C] */
-OP_MUL,/* A B C R[A] := R[B] * R[C] */
-OP_MOD,/* A B C R[A] := R[B] % R[C] */
-OP_POW,/* A B C R[A] := R[B] ^ R[C] */
-OP_DIV,/* A B C R[A] := R[B] / R[C] */
-OP_IDIV,/* A B C R[A] := R[B] // R[C] */
-
-OP_BAND,/* A B C R[A] := R[B] & R[C] */
-OP_BOR,/* A B C R[A] := R[B] | R[C] */
-OP_BXOR,/* A B C R[A] := R[B] ~ R[C] */
-OP_SHL,/* A B C R[A] := R[B] << R[C] */
-OP_SHR,/* A B C R[A] := R[B] >> R[C] */
-
-OP_MMBIN,/* A B C call C metamethod over R[A] and R[B] */
-OP_MMBINI,/* A sB C k call C metamethod over R[A] and sB */
-OP_MMBINK,/* A B C k call C metamethod over R[A] and K[B] */
-
-OP_UNM,/* A B R[A] := -R[B] */
-OP_BNOT,/* A B R[A] := ~R[B] */
-OP_NOT,/* A B R[A] := not R[B] */
-OP_LEN,/* A B R[A] := #R[B] (length operator) */
-
-OP_CONCAT,/* A B R[A] := R[A].. ... ..R[A + B - 1] */
-
-OP_CLOSE,/* A close all upvalues >= R[A] */
-OP_TBC,/* A mark variable A "to be closed" */
-OP_JMP,/* sJ pc += sJ */
-OP_EQ,/* A B k if ((R[A] == R[B]) ~= k) then pc++ */
-OP_LT,/* A B k if ((R[A] < R[B]) ~= k) then pc++ */
-OP_LE,/* A B k if ((R[A] <= R[B]) ~= k) then pc++ */
-
-OP_EQK,/* A B k if ((R[A] == K[B]) ~= k) then pc++ */
-OP_EQI,/* A sB k if ((R[A] == sB) ~= k) then pc++ */
-OP_LTI,/* A sB k if ((R[A] < sB) ~= k) then pc++ */
-OP_LEI,/* A sB k if ((R[A] <= sB) ~= k) then pc++ */
-OP_GTI,/* A sB k if ((R[A] > sB) ~= k) then pc++ */
-OP_GEI,/* A sB k if ((R[A] >= sB) ~= k) then pc++ */
-
-OP_TEST,/* A k if (not R[A] == k) then pc++ */
-OP_TESTSET,/* A B k if (not R[B] == k) then pc++ else R[A] := R[B] */
-
-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 k return R[A](R[A+1], ... ,R[A+B-1]) */
-
-OP_RETURN,/* A B C k return R[A], ... ,R[A+B-2] */
-OP_RETURN0,/* return */
-OP_RETURN1,/* A return R[A] */
-
-OP_FORLOOP,/* A Bx update counters; if loop continues then pc-=Bx; */
-OP_FORPREP,/* A Bx ;
- if not to run then pc+=Bx+1; */
-
-OP_TFORPREP,/* A Bx create upvalue for R[A + 3]; pc+=Bx */
-OP_TFORCALL,/* A C R[A+4], ... ,R[A+3+C] := R[A](R[A+1], R[A+2]); */
-OP_TFORLOOP,/* A Bx if R[A+2] ~= nil then { R[A]=R[A+2]; pc -= Bx } */
-
-OP_SETLIST,/* A vB vC k R[A][vC+i] := R[A+i], 1 <= i <= vB */
-
-OP_CLOSURE,/* A Bx R[A] := closure(KPROTO[Bx]) */
-
-OP_VARARG,/* A B C k R[A], ..., R[A+C-2] = varargs */
-
-OP_GETVARG, /* A B C R[A] := R[B][R[C]], R[B] is vararg parameter */
-
-OP_ERRNNIL,/* A Bx raise error if R[A] ~= nil (K[Bx - 1] is global name)*/
-
-OP_VARARGPREP,/* (adjust varargs) */
-
-OP_EXTRAARG/* Ax extra (larger) argument for previous opcode */
-} OpCode;
-
-
-#define NUM_OPCODES ((int)(OP_EXTRAARG) + 1)
-
-
-
-/*===========================================================================
- Notes:
-
- (*) Opcode OP_LFALSESKIP is used to convert a condition to a boolean
- value, in a code equivalent to (not cond ? false : true). (It
- produces false and skips the next instruction producing true.)
-
- (*) Opcodes OP_MMBIN and variants follow each arithmetic and
- bitwise opcode. If the operation succeeds, it skips this next
- opcode. Otherwise, this opcode calls the corresponding metamethod.
-
- (*) Opcode OP_TESTSET is used in short-circuit expressions that need
- both to jump and to produce a value, such as (a = b or c).
-
- (*) In OP_CALL, if (B == 0) then B = top - A. If (C == 0), then
- 'top' is set to last_result+1, so next open instruction (OP_CALL,
- OP_RETURN*, OP_SETLIST) may use 'top'.
-
- (*) In OP_VARARG, if (C == 0) then use actual number of varargs and
- set top (like in OP_CALL with C == 0). 'k' means function has a
- vararg table, which is in R[B].
-
- (*) In OP_RETURN, if (B == 0) then return up to 'top'.
-
- (*) In OP_LOADKX and OP_NEWTABLE, the next instruction is always
- OP_EXTRAARG.
-
- (*) In OP_SETLIST, if (B == 0) then real B = 'top'; if k, then
- real C = EXTRAARG _ C (the bits of EXTRAARG concatenated with the
- bits of C).
-
- (*) In OP_NEWTABLE, vB is log2 of the hash size (which is always a
- power of 2) plus 1, or zero for size zero. If not k, the array size
- is vC. Otherwise, the array size is EXTRAARG _ vC.
-
- (*) In OP_ERRNNIL, (Bx == 0) means index of global name doesn't
- fit in Bx. (So, that name is not available for the error message.)
-
- (*) For comparisons, k specifies what condition the test should accept
- (true or false).
-
- (*) In OP_MMBINI/OP_MMBINK, k means the arguments were flipped
- (the constant is the first operand).
-
- (*) All comparison and test instructions assume that the instruction
- being skipped (pc++) is a jump.
-
- (*) In instructions OP_RETURN/OP_TAILCALL, 'k' specifies that the
- function builds upvalues, which may need to be closed. C > 0 means
- the function has hidden vararg arguments, so that its 'func' must be
- corrected before returning; in this case, (C - 1) is its number of
- fixed parameters.
-
- (*) In comparisons with an immediate operand, C signals whether the
- original operand was a float. (It must be corrected in case of
- metamethods.)
-
-===========================================================================*/
-
-
-/*
-** masks for instruction properties. The format is:
-** bits 0-2: op mode
-** bit 3: instruction set register A
-** bit 4: operator is a test (next instruction must be a jump)
-** bit 5: instruction uses 'L->top' set by previous instruction (when B == 0)
-** bit 6: instruction sets 'L->top' for next instruction (when C == 0)
-** bit 7: instruction is an MM instruction (call a metamethod)
-*/
-
-LUAI_DDEC(const lu_byte luaP_opmodes[NUM_OPCODES];)
-
-#define getOpMode(m) (cast(enum OpMode, luaP_opmodes[m] & 7))
-#define testAMode(m) (luaP_opmodes[m] & (1 << 3))
-#define testTMode(m) (luaP_opmodes[m] & (1 << 4))
-#define testITMode(m) (luaP_opmodes[m] & (1 << 5))
-#define testOTMode(m) (luaP_opmodes[m] & (1 << 6))
-#define testMMMode(m) (luaP_opmodes[m] & (1 << 7))
-
-
-LUAI_FUNC int luaP_isOT (Instruction i);
-LUAI_FUNC int luaP_isIT (Instruction i);
-
-
-#endif
diff --git a/lopnames.h b/lopnames.h
deleted file mode 100644
index 0554a2e9a1..0000000000
--- a/lopnames.h
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
-** $Id: lopnames.h $
-** Opcode names
-** See Copyright Notice in lua.h
-*/
-
-#if !defined(lopnames_h)
-#define lopnames_h
-
-#include
-
-
-/* ORDER OP */
-
-static const char *const opnames[] = {
- "MOVE",
- "LOADI",
- "LOADF",
- "LOADK",
- "LOADKX",
- "LOADFALSE",
- "LFALSESKIP",
- "LOADTRUE",
- "LOADNIL",
- "GETUPVAL",
- "SETUPVAL",
- "GETTABUP",
- "GETTABLE",
- "GETI",
- "GETFIELD",
- "SETTABUP",
- "SETTABLE",
- "SETI",
- "SETFIELD",
- "NEWTABLE",
- "SELF",
- "ADDI",
- "ADDK",
- "SUBK",
- "MULK",
- "MODK",
- "POWK",
- "DIVK",
- "IDIVK",
- "BANDK",
- "BORK",
- "BXORK",
- "SHLI",
- "SHRI",
- "ADD",
- "SUB",
- "MUL",
- "MOD",
- "POW",
- "DIV",
- "IDIV",
- "BAND",
- "BOR",
- "BXOR",
- "SHL",
- "SHR",
- "MMBIN",
- "MMBINI",
- "MMBINK",
- "UNM",
- "BNOT",
- "NOT",
- "LEN",
- "CONCAT",
- "CLOSE",
- "TBC",
- "JMP",
- "EQ",
- "LT",
- "LE",
- "EQK",
- "EQI",
- "LTI",
- "LEI",
- "GTI",
- "GEI",
- "TEST",
- "TESTSET",
- "CALL",
- "TAILCALL",
- "RETURN",
- "RETURN0",
- "RETURN1",
- "FORLOOP",
- "FORPREP",
- "TFORPREP",
- "TFORCALL",
- "TFORLOOP",
- "SETLIST",
- "CLOSURE",
- "VARARG",
- "GETVARG",
- "ERRNNIL",
- "VARARGPREP",
- "EXTRAARG",
- NULL
-};
-
-#endif
-
diff --git a/loslib.c b/loslib.c
deleted file mode 100644
index b7a2b0d15f..0000000000
--- a/loslib.c
+++ /dev/null
@@ -1,432 +0,0 @@
-/*
-** $Id: loslib.c $
-** Standard Operating System library
-** See Copyright Notice in lua.h
-*/
-
-#define loslib_c
-#define LUA_LIB
-
-#include "lprefix.h"
-
-
-#include
-#include
-#include
-#include
-#include
-
-#include "lua.h"
-
-#include "lauxlib.h"
-#include "lualib.h"
-#include "llimits.h"
-
-
-/*
-** {==================================================================
-** List of valid conversion specifiers for the 'strftime' function;
-** options are grouped by length; group of length 2 start with '||'.
-** ===================================================================
-*/
-#if !defined(LUA_STRFTIMEOPTIONS) /* { */
-
-#if defined(LUA_USE_WINDOWS)
-#define LUA_STRFTIMEOPTIONS "aAbBcdHIjmMpSUwWxXyYzZ%" \
- "||" "#c#x#d#H#I#j#m#M#S#U#w#W#y#Y" /* two-char options */
-#elif defined(LUA_USE_C89) /* C89 (only 1-char options) */
-#define LUA_STRFTIMEOPTIONS "aAbBcdHIjmMpSUwWxXyYZ%"
-#else /* C99 specification */
-#define LUA_STRFTIMEOPTIONS "aAbBcCdDeFgGhHIjmMnprRStTuUVwWxXyYzZ%" \
- "||" "EcECExEXEyEY" "OdOeOHOIOmOMOSOuOUOVOwOWOy" /* two-char options */
-#endif
-
-#endif /* } */
-/* }================================================================== */
-
-
-/*
-** {==================================================================
-** Configuration for time-related stuff
-** ===================================================================
-*/
-
-/*
-** type to represent time_t in Lua
-*/
-#if !defined(LUA_NUMTIME) /* { */
-
-#define l_timet lua_Integer
-#define l_pushtime(L,t) lua_pushinteger(L,(lua_Integer)(t))
-#define l_gettime(L,arg) luaL_checkinteger(L, arg)
-
-#else /* }{ */
-
-#define l_timet lua_Number
-#define l_pushtime(L,t) lua_pushnumber(L,(lua_Number)(t))
-#define l_gettime(L,arg) luaL_checknumber(L, arg)
-
-#endif /* } */
-
-
-#if !defined(l_gmtime) /* { */
-/*
-** By default, Lua uses gmtime/localtime, except when POSIX is available,
-** where it uses gmtime_r/localtime_r
-*/
-
-#if defined(LUA_USE_POSIX) /* { */
-
-#define l_gmtime(t,r) gmtime_r(t,r)
-#define l_localtime(t,r) localtime_r(t,r)
-
-#else /* }{ */
-
-/* ISO C definitions */
-#define l_gmtime(t,r) ((void)(r)->tm_sec, gmtime(t))
-#define l_localtime(t,r) ((void)(r)->tm_sec, localtime(t))
-
-#endif /* } */
-
-#endif /* } */
-
-/* }================================================================== */
-
-
-/*
-** {==================================================================
-** Configuration for 'tmpnam':
-** By default, Lua uses tmpnam except when POSIX is available, where
-** it uses mkstemp.
-** ===================================================================
-*/
-#if !defined(lua_tmpnam) /* { */
-
-#if defined(LUA_USE_POSIX) /* { */
-
-#include
-
-#define LUA_TMPNAMBUFSIZE 32
-
-#if !defined(LUA_TMPNAMTEMPLATE)
-#define LUA_TMPNAMTEMPLATE "/tmp/lua_XXXXXX"
-#endif
-
-#define lua_tmpnam(b,e) { \
- strcpy(b, LUA_TMPNAMTEMPLATE); \
- e = mkstemp(b); \
- if (e != -1) close(e); \
- e = (e == -1); }
-
-#else /* }{ */
-
-/* ISO C definitions */
-#define LUA_TMPNAMBUFSIZE L_tmpnam
-#define lua_tmpnam(b,e) { e = (tmpnam(b) == NULL); }
-
-#endif /* } */
-
-#endif /* } */
-/* }================================================================== */
-
-
-#if !defined(l_system)
-#if defined(LUA_USE_IOS)
-/* Despite claiming to be ISO C, iOS does not implement 'system'. */
-#define l_system(cmd) ((cmd) == NULL ? 0 : -1)
-#else
-#define l_system(cmd) system(cmd) /* default definition */
-#endif
-#endif
-
-
-static int os_execute (lua_State *L) {
- const char *cmd = luaL_optstring(L, 1, NULL);
- int stat;
- errno = 0;
- stat = l_system(cmd);
- if (cmd != NULL)
- return luaL_execresult(L, stat);
- else {
- lua_pushboolean(L, stat); /* true if there is a shell */
- return 1;
- }
-}
-
-
-static int os_remove (lua_State *L) {
- const char *filename = luaL_checkstring(L, 1);
- errno = 0;
- return luaL_fileresult(L, remove(filename) == 0, filename);
-}
-
-
-static int os_rename (lua_State *L) {
- const char *fromname = luaL_checkstring(L, 1);
- const char *toname = luaL_checkstring(L, 2);
- errno = 0;
- return luaL_fileresult(L, rename(fromname, toname) == 0, NULL);
-}
-
-
-static int os_tmpname (lua_State *L) {
- char buff[LUA_TMPNAMBUFSIZE];
- int err;
- lua_tmpnam(buff, err);
- if (l_unlikely(err))
- return luaL_error(L, "unable to generate a unique filename");
- lua_pushstring(L, buff);
- return 1;
-}
-
-
-static int os_getenv (lua_State *L) {
- lua_pushstring(L, getenv(luaL_checkstring(L, 1))); /* if NULL push nil */
- return 1;
-}
-
-
-static int os_clock (lua_State *L) {
- lua_pushnumber(L, ((lua_Number)clock())/(lua_Number)CLOCKS_PER_SEC);
- return 1;
-}
-
-
-/*
-** {======================================================
-** Time/Date operations
-** { year=%Y, month=%m, day=%d, hour=%H, min=%M, sec=%S,
-** wday=%w+1, yday=%j, isdst=? }
-** =======================================================
-*/
-
-/*
-** About the overflow check: an overflow cannot occur when time
-** is represented by a lua_Integer, because either lua_Integer is
-** large enough to represent all int fields or it is not large enough
-** to represent a time that cause a field to overflow. However, if
-** times are represented as doubles and lua_Integer is int, then the
-** time 0x1.e1853b0d184f6p+55 would cause an overflow when adding 1900
-** to compute the year.
-*/
-static void setfield (lua_State *L, const char *key, int value, int delta) {
- #if (defined(LUA_NUMTIME) && LUA_MAXINTEGER <= INT_MAX)
- if (l_unlikely(value > LUA_MAXINTEGER - delta))
- luaL_error(L, "field '%s' is out-of-bound", key);
- #endif
- lua_pushinteger(L, (lua_Integer)value + delta);
- lua_setfield(L, -2, key);
-}
-
-
-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);
-}
-
-
-/*
-** Set all fields from structure 'tm' in the table on top of the stack
-*/
-static void setallfields (lua_State *L, struct tm *stm) {
- setfield(L, "year", stm->tm_year, 1900);
- setfield(L, "month", stm->tm_mon, 1);
- setfield(L, "day", stm->tm_mday, 0);
- setfield(L, "hour", stm->tm_hour, 0);
- setfield(L, "min", stm->tm_min, 0);
- setfield(L, "sec", stm->tm_sec, 0);
- setfield(L, "yday", stm->tm_yday, 1);
- setfield(L, "wday", stm->tm_wday, 1);
- setboolfield(L, "isdst", stm->tm_isdst);
-}
-
-
-static int getboolfield (lua_State *L, const char *key) {
- int res;
- res = (lua_getfield(L, -1, key) == LUA_TNIL) ? -1 : lua_toboolean(L, -1);
- lua_pop(L, 1);
- return res;
-}
-
-
-static int getfield (lua_State *L, const char *key, int d, int delta) {
- int isnum;
- int t = lua_getfield(L, -1, key); /* get field and its type */
- lua_Integer res = lua_tointegerx(L, -1, &isnum);
- if (!isnum) { /* field is not an integer? */
- if (l_unlikely(t != LUA_TNIL)) /* some other value? */
- return luaL_error(L, "field '%s' is not an integer", key);
- else if (l_unlikely(d < 0)) /* absent field; no default? */
- return luaL_error(L, "field '%s' missing in date table", key);
- res = d;
- }
- else {
- if (!(res >= 0 ? res - delta <= INT_MAX : INT_MIN + delta <= res))
- return luaL_error(L, "field '%s' is out-of-bound", key);
- res -= delta;
- }
- lua_pop(L, 1);
- return (int)res;
-}
-
-
-static const char *checkoption (lua_State *L, const char *conv,
- size_t convlen, char *buff) {
- const char *option = LUA_STRFTIMEOPTIONS;
- unsigned oplen = 1; /* length of options being checked */
- for (; *option != '\0' && oplen <= convlen; option += oplen) {
- if (*option == '|') /* next block? */
- oplen++; /* will check options with next length (+1) */
- else if (memcmp(conv, option, oplen) == 0) { /* match? */
- memcpy(buff, conv, oplen); /* copy valid option to buffer */
- buff[oplen] = '\0';
- return conv + oplen; /* return next item */
- }
- }
- luaL_argerror(L, 1,
- lua_pushfstring(L, "invalid conversion specifier '%%%s'", conv));
- return conv; /* to avoid warnings */
-}
-
-
-static time_t l_checktime (lua_State *L, int arg) {
- l_timet t = l_gettime(L, arg);
- luaL_argcheck(L, (time_t)t == t, arg, "time out-of-bounds");
- return (time_t)t;
-}
-
-
-/* maximum size for an individual 'strftime' item */
-#define SIZETIMEFMT 250
-
-
-static int os_date (lua_State *L) {
- size_t slen;
- const char *s = luaL_optlstring(L, 1, "%c", &slen);
- time_t t = luaL_opt(L, l_checktime, 2, time(NULL));
- const char *se = s + slen; /* 's' end */
- struct tm tmr, *stm;
- if (*s == '!') { /* UTC? */
- stm = l_gmtime(&t, &tmr);
- s++; /* skip '!' */
- }
- else
- stm = l_localtime(&t, &tmr);
- if (stm == NULL) /* invalid date? */
- return luaL_error(L,
- "date result cannot be represented in this installation");
- if (strcmp(s, "*t") == 0) {
- lua_createtable(L, 0, 9); /* 9 = number of fields */
- setallfields(L, stm);
- }
- else {
- char cc[4]; /* buffer for individual conversion specifiers */
- luaL_Buffer b;
- cc[0] = '%';
- luaL_buffinit(L, &b);
- while (s < se) {
- if (*s != '%') /* not a conversion specifier? */
- luaL_addchar(&b, *s++);
- else {
- size_t reslen;
- char *buff = luaL_prepbuffsize(&b, SIZETIMEFMT);
- s++; /* skip '%' */
- /* copy specifier to 'cc' */
- s = checkoption(L, s, ct_diff2sz(se - s), cc + 1);
- reslen = strftime(buff, SIZETIMEFMT, cc, stm);
- luaL_addsize(&b, reslen);
- }
- }
- luaL_pushresult(&b);
- }
- return 1;
-}
-
-
-static int os_time (lua_State *L) {
- time_t t;
- if (lua_isnoneornil(L, 1)) /* called without args? */
- t = time(NULL); /* get current time */
- else {
- struct tm ts;
- luaL_checktype(L, 1, LUA_TTABLE);
- lua_settop(L, 1); /* make sure table is at the top */
- ts.tm_year = getfield(L, "year", -1, 1900);
- ts.tm_mon = getfield(L, "month", -1, 1);
- ts.tm_mday = getfield(L, "day", -1, 0);
- ts.tm_hour = getfield(L, "hour", 12, 0);
- ts.tm_min = getfield(L, "min", 0, 0);
- ts.tm_sec = getfield(L, "sec", 0, 0);
- ts.tm_isdst = getboolfield(L, "isdst");
- t = mktime(&ts);
- setallfields(L, &ts); /* update fields with normalized values */
- }
- if (t != (time_t)(l_timet)t || t == (time_t)(-1))
- return luaL_error(L,
- "time result cannot be represented in this installation");
- l_pushtime(L, t);
- return 1;
-}
-
-
-static int os_difftime (lua_State *L) {
- time_t t1 = l_checktime(L, 1);
- time_t t2 = l_checktime(L, 2);
- lua_pushnumber(L, (lua_Number)difftime(t1, t2));
- return 1;
-}
-
-/* }====================================================== */
-
-
-static int os_setlocale (lua_State *L) {
- static const int cat[] = {LC_ALL, LC_COLLATE, LC_CTYPE, LC_MONETARY,
- LC_NUMERIC, LC_TIME};
- static const char *const catnames[] = {"all", "collate", "ctype", "monetary",
- "numeric", "time", NULL};
- const char *l = luaL_optstring(L, 1, NULL);
- int op = luaL_checkoption(L, 2, "all", catnames);
- lua_pushstring(L, setlocale(cat[op], l));
- return 1;
-}
-
-
-static int os_exit (lua_State *L) {
- int status;
- if (lua_isboolean(L, 1))
- status = (lua_toboolean(L, 1) ? EXIT_SUCCESS : EXIT_FAILURE);
- else
- status = (int)luaL_optinteger(L, 1, EXIT_SUCCESS);
- if (lua_toboolean(L, 2))
- lua_close(L);
- if (L) exit(status); /* 'if' to avoid warnings for unreachable 'return' */
- return 0;
-}
-
-
-static const luaL_Reg syslib[] = {
- {"clock", os_clock},
- {"date", os_date},
- {"difftime", os_difftime},
- {"execute", os_execute},
- {"exit", os_exit},
- {"getenv", os_getenv},
- {"remove", os_remove},
- {"rename", os_rename},
- {"setlocale", os_setlocale},
- {"time", os_time},
- {"tmpname", os_tmpname},
- {NULL, NULL}
-};
-
-/* }====================================================== */
-
-
-
-LUAMOD_API int luaopen_os (lua_State *L) {
- luaL_newlib(L, syslib);
- return 1;
-}
-
diff --git a/lparser.c b/lparser.c
deleted file mode 100644
index 6b87773ea3..0000000000
--- a/lparser.c
+++ /dev/null
@@ -1,2202 +0,0 @@
-/*
-** $Id: lparser.c $
-** Lua Parser
-** See Copyright Notice in lua.h
-*/
-
-#define lparser_c
-#define LUA_CORE
-
-#include "lprefix.h"
-
-
-#include
-#include
-
-#include "lua.h"
-
-#include "lcode.h"
-#include "ldebug.h"
-#include "ldo.h"
-#include "lfunc.h"
-#include "llex.h"
-#include "lmem.h"
-#include "lobject.h"
-#include "lopcodes.h"
-#include "lparser.h"
-#include "lstate.h"
-#include "lstring.h"
-#include "ltable.h"
-
-
-
-/* maximum number of variable declarations per function (must be
- smaller than 250, due to the bytecode format) */
-#define MAXVARS 200
-
-
-#define hasmultret(k) ((k) == VCALL || (k) == VVARARG)
-
-
-/* because all strings are unified by the scanner, the parser
- can use pointer equality for string equality */
-#define eqstr(a,b) ((a) == (b))
-
-
-/*
-** nodes for block list (list of active blocks)
-*/
-typedef struct BlockCnt {
- struct BlockCnt *previous; /* chain */
- int firstlabel; /* index of first label in this block */
- int firstgoto; /* index of first pending goto in this block */
- short nactvar; /* number of active declarations at block entry */
- lu_byte upval; /* true if some variable in the block is an upvalue */
- lu_byte isloop; /* 1 if 'block' is a loop; 2 if it has pending breaks */
- lu_byte insidetbc; /* true if inside the scope of a to-be-closed var. */
-} BlockCnt;
-
-
-
-/*
-** prototypes for recursive non-terminal functions
-*/
-static void statement (LexState *ls);
-static void expr (LexState *ls, expdesc *v);
-
-
-static l_noret error_expected (LexState *ls, int token) {
- luaX_syntaxerror(ls,
- luaO_pushfstring(ls->L, "%s expected", luaX_token2str(ls, token)));
-}
-
-
-static l_noret errorlimit (FuncState *fs, int limit, const char *what) {
- lua_State *L = fs->ls->L;
- const char *msg;
- int line = fs->f->linedefined;
- const char *where = (line == 0)
- ? "main function"
- : luaO_pushfstring(L, "function at line %d", line);
- msg = luaO_pushfstring(L, "too many %s (limit is %d) in %s",
- what, limit, where);
- luaX_syntaxerror(fs->ls, msg);
-}
-
-
-void luaY_checklimit (FuncState *fs, int v, int l, const char *what) {
- if (l_unlikely(v > l)) errorlimit(fs, l, what);
-}
-
-
-/*
-** Test whether next token is 'c'; if so, skip it.
-*/
-static int testnext (LexState *ls, int c) {
- if (ls->t.token == c) {
- luaX_next(ls);
- return 1;
- }
- else return 0;
-}
-
-
-/*
-** Check that next token is 'c'.
-*/
-static void check (LexState *ls, int c) {
- if (ls->t.token != c)
- error_expected(ls, c);
-}
-
-
-/*
-** Check that next token is 'c' and skip it.
-*/
-static void checknext (LexState *ls, int c) {
- check(ls, c);
- luaX_next(ls);
-}
-
-
-#define check_condition(ls,c,msg) { if (!(c)) luaX_syntaxerror(ls, msg); }
-
-
-/*
-** Check that next token is 'what' and skip it. In case of error,
-** raise an error that the expected 'what' should match a 'who'
-** in line 'where' (if that is not the current line).
-*/
-static void check_match (LexState *ls, int what, int who, int where) {
- if (l_unlikely(!testnext(ls, what))) {
- if (where == ls->linenumber) /* all in the same line? */
- error_expected(ls, what); /* do not need a complex message */
- else {
- luaX_syntaxerror(ls, luaO_pushfstring(ls->L,
- "%s expected (to close %s at line %d)",
- luaX_token2str(ls, what), luaX_token2str(ls, who), where));
- }
- }
-}
-
-
-static TString *str_checkname (LexState *ls) {
- TString *ts;
- check(ls, TK_NAME);
- ts = ls->t.seminfo.ts;
- luaX_next(ls);
- return ts;
-}
-
-
-static void init_exp (expdesc *e, expkind k, int i) {
- e->f = e->t = NO_JUMP;
- e->k = k;
- e->u.info = i;
-}
-
-
-static void codestring (expdesc *e, TString *s) {
- e->f = e->t = NO_JUMP;
- e->k = VKSTR;
- e->u.strval = s;
-}
-
-
-static void codename (LexState *ls, expdesc *e) {
- codestring(e, str_checkname(ls));
-}
-
-
-/*
-** Register a new local variable in the active 'Proto' (for debug
-** information).
-*/
-static short registerlocalvar (LexState *ls, FuncState *fs,
- TString *varname) {
- Proto *f = fs->f;
- int oldsize = f->sizelocvars;
- luaM_growvector(ls->L, f->locvars, fs->ndebugvars, f->sizelocvars,
- LocVar, SHRT_MAX, "local variables");
- while (oldsize < f->sizelocvars)
- f->locvars[oldsize++].varname = NULL;
- f->locvars[fs->ndebugvars].varname = varname;
- f->locvars[fs->ndebugvars].startpc = fs->pc;
- luaC_objbarrier(ls->L, f, varname);
- return fs->ndebugvars++;
-}
-
-
-/*
-** Create a new variable with the given 'name' and given 'kind'.
-** Return its index in the function.
-*/
-static int new_varkind (LexState *ls, TString *name, lu_byte kind) {
- lua_State *L = ls->L;
- FuncState *fs = ls->fs;
- Dyndata *dyd = ls->dyd;
- Vardesc *var;
- luaM_growvector(L, dyd->actvar.arr, dyd->actvar.n + 1,
- dyd->actvar.size, Vardesc, SHRT_MAX, "variable declarations");
- var = &dyd->actvar.arr[dyd->actvar.n++];
- var->vd.kind = kind; /* default */
- var->vd.name = name;
- return dyd->actvar.n - 1 - fs->firstlocal;
-}
-
-
-/*
-** Create a new local variable with the given 'name' and regular kind.
-*/
-static int new_localvar (LexState *ls, TString *name) {
- return new_varkind(ls, name, VDKREG);
-}
-
-#define new_localvarliteral(ls,v) \
- new_localvar(ls, \
- luaX_newstring(ls, "" v, (sizeof(v)/sizeof(char)) - 1));
-
-
-
-/*
-** Return the "variable description" (Vardesc) of a given variable.
-** (Unless noted otherwise, all variables are referred to by their
-** compiler indices.)
-*/
-static Vardesc *getlocalvardesc (FuncState *fs, int vidx) {
- return &fs->ls->dyd->actvar.arr[fs->firstlocal + vidx];
-}
-
-
-/*
-** Convert 'nvar', a compiler index level, to its corresponding
-** register. For that, search for the highest variable below that level
-** that is in a register and uses its register index ('ridx') plus one.
-*/
-static lu_byte reglevel (FuncState *fs, int nvar) {
- while (nvar-- > 0) {
- Vardesc *vd = getlocalvardesc(fs, nvar); /* get previous variable */
- if (varinreg(vd)) /* is in a register? */
- return cast_byte(vd->vd.ridx + 1);
- }
- return 0; /* no variables in registers */
-}
-
-
-/*
-** Return the number of variables in the register stack for the given
-** function.
-*/
-lu_byte luaY_nvarstack (FuncState *fs) {
- return reglevel(fs, fs->nactvar);
-}
-
-
-/*
-** Get the debug-information entry for current variable 'vidx'.
-*/
-static LocVar *localdebuginfo (FuncState *fs, int vidx) {
- Vardesc *vd = getlocalvardesc(fs, vidx);
- if (!varinreg(vd))
- return NULL; /* no debug info. for constants */
- else {
- int idx = vd->vd.pidx;
- lua_assert(idx < fs->ndebugvars);
- return &fs->f->locvars[idx];
- }
-}
-
-
-/*
-** Create an expression representing variable 'vidx'
-*/
-static void init_var (FuncState *fs, expdesc *e, int vidx) {
- e->f = e->t = NO_JUMP;
- e->k = VLOCAL;
- e->u.var.vidx = cast_short(vidx);
- e->u.var.ridx = getlocalvardesc(fs, vidx)->vd.ridx;
-}
-
-
-/*
-** Raises an error if variable described by 'e' is read only; moreover,
-** if 'e' is t[exp] where t is the vararg parameter, change it to index
-** a real table. (Virtual vararg tables cannot be changed.)
-*/
-static void check_readonly (LexState *ls, expdesc *e) {
- FuncState *fs = ls->fs;
- TString *varname = NULL; /* to be set if variable is const */
- switch (e->k) {
- case VCONST: {
- varname = ls->dyd->actvar.arr[e->u.info].vd.name;
- break;
- }
- case VLOCAL: case VVARGVAR: {
- Vardesc *vardesc = getlocalvardesc(fs, e->u.var.vidx);
- if (vardesc->vd.kind != VDKREG) /* not a regular variable? */
- varname = vardesc->vd.name;
- break;
- }
- case VUPVAL: {
- Upvaldesc *up = &fs->f->upvalues[e->u.info];
- if (up->kind != VDKREG)
- varname = up->name;
- break;
- }
- case VVARGIND: {
- needvatab(fs->f); /* function will need a vararg table */
- e->k = VINDEXED;
- } /* FALLTHROUGH */
- case VINDEXUP: case VINDEXSTR: case VINDEXED: { /* global variable */
- if (e->u.ind.ro) /* read-only? */
- varname = tsvalue(&fs->f->k[e->u.ind.keystr]);
- break;
- }
- default:
- lua_assert(e->k == VINDEXI); /* this one doesn't need any check */
- return; /* integer index cannot be read-only */
- }
- if (varname)
- luaK_semerror(ls, "attempt to assign to const variable '%s'",
- getstr(varname));
-}
-
-
-/*
-** Start the scope for the last 'nvars' created variables.
-*/
-static void adjustlocalvars (LexState *ls, int nvars) {
- FuncState *fs = ls->fs;
- int reglevel = luaY_nvarstack(fs);
- int i;
- for (i = 0; i < nvars; i++) {
- int vidx = fs->nactvar++;
- Vardesc *var = getlocalvardesc(fs, vidx);
- var->vd.ridx = cast_byte(reglevel++);
- var->vd.pidx = registerlocalvar(ls, fs, var->vd.name);
- luaY_checklimit(fs, reglevel, MAXVARS, "local variables");
- }
-}
-
-
-/*
-** Close the scope for all variables up to level 'tolevel'.
-** (debug info.)
-*/
-static void removevars (FuncState *fs, int tolevel) {
- fs->ls->dyd->actvar.n -= (fs->nactvar - tolevel);
- while (fs->nactvar > tolevel) {
- LocVar *var = localdebuginfo(fs, --fs->nactvar);
- if (var) /* does it have debug information? */
- var->endpc = fs->pc;
- }
-}
-
-
-/*
-** Search the upvalues of the function 'fs' for one
-** with the given 'name'.
-*/
-static int searchupvalue (FuncState *fs, TString *name) {
- int i;
- Upvaldesc *up = fs->f->upvalues;
- for (i = 0; i < fs->nups; i++) {
- if (eqstr(up[i].name, name)) return i;
- }
- return -1; /* not found */
-}
-
-
-static Upvaldesc *allocupvalue (FuncState *fs) {
- Proto *f = fs->f;
- int oldsize = f->sizeupvalues;
- luaY_checklimit(fs, fs->nups + 1, MAXUPVAL, "upvalues");
- luaM_growvector(fs->ls->L, f->upvalues, fs->nups, f->sizeupvalues,
- Upvaldesc, MAXUPVAL, "upvalues");
- while (oldsize < f->sizeupvalues)
- f->upvalues[oldsize++].name = NULL;
- return &f->upvalues[fs->nups++];
-}
-
-
-static int newupvalue (FuncState *fs, TString *name, expdesc *v) {
- Upvaldesc *up = allocupvalue(fs);
- FuncState *prev = fs->prev;
- if (v->k == VLOCAL) {
- up->instack = 1;
- up->idx = v->u.var.ridx;
- up->kind = getlocalvardesc(prev, v->u.var.vidx)->vd.kind;
- lua_assert(eqstr(name, getlocalvardesc(prev, v->u.var.vidx)->vd.name));
- }
- else {
- up->instack = 0;
- up->idx = cast_byte(v->u.info);
- up->kind = prev->f->upvalues[v->u.info].kind;
- lua_assert(eqstr(name, prev->f->upvalues[v->u.info].name));
- }
- up->name = name;
- luaC_objbarrier(fs->ls->L, fs->f, name);
- return fs->nups - 1;
-}
-
-
-/*
-** Look for an active variable with the name 'n' in the
-** function 'fs'. If found, initialize 'var' with it and return
-** its expression kind; otherwise return -1. While searching,
-** var->u.info==-1 means that the preambular global declaration is
-** active (the default while there is no other global declaration);
-** var->u.info==-2 means there is no active collective declaration
-** (some previous global declaration but no collective declaration);
-** and var->u.info>=0 points to the inner-most (the first one found)
-** collective declaration, if there is one.
-*/
-static int searchvar (FuncState *fs, TString *n, expdesc *var) {
- int i;
- for (i = cast_int(fs->nactvar) - 1; i >= 0; i--) {
- Vardesc *vd = getlocalvardesc(fs, i);
- if (varglobal(vd)) { /* global declaration? */
- if (vd->vd.name == NULL) { /* collective declaration? */
- if (var->u.info < 0) /* no previous collective declaration? */
- var->u.info = fs->firstlocal + i; /* this is the first one */
- }
- else { /* global name */
- if (eqstr(n, vd->vd.name)) { /* found? */
- init_exp(var, VGLOBAL, fs->firstlocal + i);
- return VGLOBAL;
- }
- else if (var->u.info == -1) /* active preambular declaration? */
- var->u.info = -2; /* invalidate preambular declaration */
- }
- }
- else if (eqstr(n, vd->vd.name)) { /* found? */
- if (vd->vd.kind == RDKCTC) /* compile-time constant? */
- init_exp(var, VCONST, fs->firstlocal + i);
- else { /* local variable */
- init_var(fs, var, i);
- if (vd->vd.kind == RDKVAVAR) /* vararg parameter? */
- var->k = VVARGVAR;
- }
- return cast_int(var->k);
- }
- }
- return -1; /* not found */
-}
-
-
-/*
-** Mark block where variable at given level was defined
-** (to emit close instructions later).
-*/
-static void markupval (FuncState *fs, int level) {
- BlockCnt *bl = fs->bl;
- while (bl->nactvar > level)
- bl = bl->previous;
- bl->upval = 1;
- fs->needclose = 1;
-}
-
-
-/*
-** Mark that current block has a to-be-closed variable.
-*/
-static void marktobeclosed (FuncState *fs) {
- BlockCnt *bl = fs->bl;
- bl->upval = 1;
- bl->insidetbc = 1;
- fs->needclose = 1;
-}
-
-
-/*
-** Find a variable with the given name 'n'. If it is an upvalue, add
-** this upvalue into all intermediate functions. If it is a global, set
-** 'var' as 'void' as a flag.
-*/
-static void singlevaraux (FuncState *fs, TString *n, expdesc *var, int base) {
- int v = searchvar(fs, n, var); /* look up variables at current level */
- if (v >= 0) { /* found? */
- if (!base) {
- if (var->k == VVARGVAR) /* vararg parameter? */
- luaK_vapar2local(fs, var); /* change it to a regular local */
- if (var->k == VLOCAL)
- markupval(fs, var->u.var.vidx); /* will be used as an upvalue */
- }
- /* else nothing else to be done */
- }
- else { /* not found at current level; try upvalues */
- int idx = searchupvalue(fs, n); /* try existing upvalues */
- if (idx < 0) { /* not found? */
- if (fs->prev != NULL) /* more levels? */
- singlevaraux(fs->prev, n, var, 0); /* try upper levels */
- if (var->k == VLOCAL || var->k == VUPVAL) /* local or upvalue? */
- idx = newupvalue(fs, n, var); /* will be a new upvalue */
- else /* it is a global or a constant */
- return; /* don't need to do anything at this level */
- }
- init_exp(var, VUPVAL, idx); /* new or old upvalue */
- }
-}
-
-
-static void buildglobal (LexState *ls, TString *varname, expdesc *var) {
- FuncState *fs = ls->fs;
- expdesc key;
- init_exp(var, VGLOBAL, -1); /* global by default */
- singlevaraux(fs, ls->envn, var, 1); /* get environment variable */
- if (var->k == VGLOBAL)
- luaK_semerror(ls, "%s is global when accessing variable '%s'",
- LUA_ENV, getstr(varname));
- luaK_exp2anyregup(fs, var); /* _ENV could be a constant */
- codestring(&key, varname); /* key is variable name */
- luaK_indexed(fs, var, &key); /* 'var' represents _ENV[varname] */
-}
-
-
-/*
-** Find a variable with the given name 'n', handling global variables
-** too.
-*/
-static void buildvar (LexState *ls, TString *varname, expdesc *var) {
- FuncState *fs = ls->fs;
- init_exp(var, VGLOBAL, -1); /* global by default */
- singlevaraux(fs, varname, var, 1);
- if (var->k == VGLOBAL) { /* global name? */
- int info = var->u.info;
- /* global by default in the scope of a global declaration? */
- if (info == -2)
- luaK_semerror(ls, "variable '%s' not declared", getstr(varname));
- buildglobal(ls, varname, var);
- if (info != -1 && ls->dyd->actvar.arr[info].vd.kind == GDKCONST)
- var->u.ind.ro = 1; /* mark variable as read-only */
- else /* anyway must be a global */
- lua_assert(info == -1 || ls->dyd->actvar.arr[info].vd.kind == GDKREG);
- }
-}
-
-
-static void singlevar (LexState *ls, expdesc *var) {
- buildvar(ls, str_checkname(ls), var);
-}
-
-
-/*
-** Adjust the number of results from an expression list 'e' with 'nexps'
-** expressions to 'nvars' values.
-*/
-static void adjust_assign (LexState *ls, int nvars, int nexps, expdesc *e) {
- FuncState *fs = ls->fs;
- int needed = nvars - nexps; /* extra values needed */
- luaK_checkstack(fs, needed);
- if (hasmultret(e->k)) { /* last expression has multiple returns? */
- int extra = needed + 1; /* discount last expression itself */
- if (extra < 0)
- extra = 0;
- luaK_setreturns(fs, e, extra); /* last exp. provides the difference */
- }
- else {
- if (e->k != VVOID) /* at least one expression? */
- luaK_exp2nextreg(fs, e); /* close last expression */
- if (needed > 0) /* missing values? */
- luaK_nil(fs, fs->freereg, needed); /* complete with nils */
- }
- if (needed > 0)
- luaK_reserveregs(fs, needed); /* registers for extra values */
- else /* adding 'needed' is actually a subtraction */
- fs->freereg = cast_byte(fs->freereg + needed); /* remove extra values */
-}
-
-
-#define enterlevel(ls) luaE_incCstack(ls->L)
-
-
-#define leavelevel(ls) ((ls)->L->nCcalls--)
-
-
-/*
-** Generates an error that a goto jumps into the scope of some
-** variable declaration.
-*/
-static l_noret jumpscopeerror (LexState *ls, Labeldesc *gt) {
- TString *tsname = getlocalvardesc(ls->fs, gt->nactvar)->vd.name;
- const char *varname = (tsname != NULL) ? getstr(tsname) : "*";
- luaK_semerror(ls,
- " at line %d jumps into the scope of '%s'",
- getstr(gt->name), gt->line, varname); /* raise the error */
-}
-
-
-/*
-** Closes the goto at index 'g' to given 'label' and removes it
-** from the list of pending gotos.
-** If it jumps into the scope of some variable, raises an error.
-** The goto needs a CLOSE if it jumps out of a block with upvalues,
-** or out of the scope of some variable and the block has upvalues
-** (signaled by parameter 'bup').
-*/
-static void closegoto (LexState *ls, int g, Labeldesc *label, int bup) {
- int i;
- FuncState *fs = ls->fs;
- Labellist *gl = &ls->dyd->gt; /* list of gotos */
- Labeldesc *gt = &gl->arr[g]; /* goto to be resolved */
- lua_assert(eqstr(gt->name, label->name));
- if (l_unlikely(gt->nactvar < label->nactvar)) /* enter some scope? */
- jumpscopeerror(ls, gt);
- if (gt->close ||
- (label->nactvar < gt->nactvar && bup)) { /* needs close? */
- lu_byte stklevel = reglevel(fs, label->nactvar);
- /* move jump to CLOSE position */
- fs->f->code[gt->pc + 1] = fs->f->code[gt->pc];
- /* put CLOSE instruction at original position */
- fs->f->code[gt->pc] = CREATE_ABCk(OP_CLOSE, stklevel, 0, 0, 0);
- gt->pc++; /* must point to jump instruction */
- }
- luaK_patchlist(ls->fs, gt->pc, label->pc); /* goto jumps to label */
- for (i = g; i < gl->n - 1; i++) /* remove goto from pending list */
- gl->arr[i] = gl->arr[i + 1];
- gl->n--;
-}
-
-
-/*
-** Search for an active label with the given name, starting at
-** index 'ilb' (so that it can search for all labels in current block
-** or all labels in current function).
-*/
-static Labeldesc *findlabel (LexState *ls, TString *name, int ilb) {
- Dyndata *dyd = ls->dyd;
- for (; ilb < dyd->label.n; ilb++) {
- Labeldesc *lb = &dyd->label.arr[ilb];
- if (eqstr(lb->name, name)) /* correct label? */
- return lb;
- }
- return NULL; /* label not found */
-}
-
-
-/*
-** Adds a new label/goto in the corresponding list.
-*/
-static int newlabelentry (LexState *ls, Labellist *l, TString *name,
- int line, int pc) {
- int n = l->n;
- luaM_growvector(ls->L, l->arr, n, l->size,
- Labeldesc, SHRT_MAX, "labels/gotos");
- l->arr[n].name = name;
- l->arr[n].line = line;
- l->arr[n].nactvar = ls->fs->nactvar;
- l->arr[n].close = 0;
- l->arr[n].pc = pc;
- l->n = n + 1;
- return n;
-}
-
-
-/*
-** Create an entry for the goto and the code for it. As it is not known
-** at this point whether the goto may need a CLOSE, the code has a jump
-** followed by an CLOSE. (As the CLOSE comes after the jump, it is a
-** dead instruction; it works as a placeholder.) When the goto is closed
-** against a label, if it needs a CLOSE, the two instructions swap
-** positions, so that the CLOSE comes before the jump.
-*/
-static int newgotoentry (LexState *ls, TString *name, int line) {
- FuncState *fs = ls->fs;
- int pc = luaK_jump(fs); /* create jump */
- luaK_codeABC(fs, OP_CLOSE, 0, 1, 0); /* spaceholder, marked as dead */
- return newlabelentry(ls, &ls->dyd->gt, name, line, pc);
-}
-
-
-/*
-** Create a new label with the given 'name' at the given 'line'.
-** 'last' tells whether label is the last non-op statement in its
-** block. Solves all pending gotos to this new label and adds
-** a close instruction if necessary.
-** Returns true iff it added a close instruction.
-*/
-static void createlabel (LexState *ls, TString *name, int line, int last) {
- FuncState *fs = ls->fs;
- Labellist *ll = &ls->dyd->label;
- int l = newlabelentry(ls, ll, name, line, luaK_getlabel(fs));
- if (last) { /* label is last no-op statement in the block? */
- /* assume that locals are already out of scope */
- ll->arr[l].nactvar = fs->bl->nactvar;
- }
-}
-
-
-/*
-** Traverse the pending gotos of the finishing block checking whether
-** each match some label of that block. Those that do not match are
-** "exported" to the outer block, to be solved there. In particular,
-** its 'nactvar' is updated with the level of the inner block,
-** as the variables of the inner block are now out of scope.
-*/
-static void solvegotos (FuncState *fs, BlockCnt *bl) {
- LexState *ls = fs->ls;
- Labellist *gl = &ls->dyd->gt;
- int outlevel = reglevel(fs, bl->nactvar); /* level outside the block */
- int igt = bl->firstgoto; /* first goto in the finishing block */
- while (igt < gl->n) { /* for each pending goto */
- Labeldesc *gt = &gl->arr[igt];
- /* search for a matching label in the current block */
- Labeldesc *lb = findlabel(ls, gt->name, bl->firstlabel);
- if (lb != NULL) /* found a match? */
- closegoto(ls, igt, lb, bl->upval); /* close and remove goto */
- else { /* adjust 'goto' for outer block */
- /* block has variables to be closed and goto escapes the scope of
- some variable? */
- if (bl->upval && reglevel(fs, gt->nactvar) > outlevel)
- gt->close = 1; /* jump may need a close */
- gt->nactvar = bl->nactvar; /* correct level for outer block */
- igt++; /* go to next goto */
- }
- }
- ls->dyd->label.n = bl->firstlabel; /* remove local labels */
-}
-
-
-static void enterblock (FuncState *fs, BlockCnt *bl, lu_byte isloop) {
- bl->isloop = isloop;
- bl->nactvar = fs->nactvar;
- bl->firstlabel = fs->ls->dyd->label.n;
- bl->firstgoto = fs->ls->dyd->gt.n;
- bl->upval = 0;
- /* inherit 'insidetbc' from enclosing block */
- bl->insidetbc = (fs->bl != NULL && fs->bl->insidetbc);
- bl->previous = fs->bl; /* link block in function's block list */
- fs->bl = bl;
- lua_assert(fs->freereg == luaY_nvarstack(fs));
-}
-
-
-/*
-** generates an error for an undefined 'goto'.
-*/
-static l_noret undefgoto (LexState *ls, Labeldesc *gt) {
- /* breaks are checked when created, cannot be undefined */
- lua_assert(!eqstr(gt->name, ls->brkn));
- luaK_semerror(ls, "no visible label '%s' for at line %d",
- getstr(gt->name), gt->line);
-}
-
-
-static void leaveblock (FuncState *fs) {
- BlockCnt *bl = fs->bl;
- LexState *ls = fs->ls;
- lu_byte stklevel = reglevel(fs, bl->nactvar); /* level outside block */
- if (bl->previous && bl->upval) /* need a 'close'? */
- luaK_codeABC(fs, OP_CLOSE, stklevel, 0, 0);
- fs->freereg = stklevel; /* free registers */
- removevars(fs, bl->nactvar); /* remove block locals */
- lua_assert(bl->nactvar == fs->nactvar); /* back to level on entry */
- if (bl->isloop == 2) /* has to fix pending breaks? */
- createlabel(ls, ls->brkn, 0, 0);
- solvegotos(fs, bl);
- if (bl->previous == NULL) { /* was it the last block? */
- if (bl->firstgoto < ls->dyd->gt.n) /* still pending gotos? */
- undefgoto(ls, &ls->dyd->gt.arr[bl->firstgoto]); /* error */
- }
- fs->bl = bl->previous; /* current block now is previous one */
-}
-
-
-/*
-** adds a new prototype into list of prototypes
-*/
-static Proto *addprototype (LexState *ls) {
- Proto *clp;
- lua_State *L = ls->L;
- FuncState *fs = ls->fs;
- Proto *f = fs->f; /* prototype of current function */
- if (fs->np >= f->sizep) {
- int oldsize = f->sizep;
- luaM_growvector(L, f->p, fs->np, f->sizep, Proto *, MAXARG_Bx, "functions");
- while (oldsize < f->sizep)
- f->p[oldsize++] = NULL;
- }
- f->p[fs->np++] = clp = luaF_newproto(L);
- luaC_objbarrier(L, f, clp);
- return clp;
-}
-
-
-/*
-** codes instruction to create new closure in parent function.
-** The OP_CLOSURE instruction uses the last available register,
-** so that, if it invokes the GC, the GC knows which registers
-** are in use at that time.
-
-*/
-static void codeclosure (LexState *ls, expdesc *v) {
- FuncState *fs = ls->fs->prev;
- init_exp(v, VRELOC, luaK_codeABx(fs, OP_CLOSURE, 0, fs->np - 1));
- luaK_exp2nextreg(fs, v); /* fix it at the last register */
-}
-
-
-static void open_func (LexState *ls, FuncState *fs, BlockCnt *bl) {
- lua_State *L = ls->L;
- Proto *f = fs->f;
- fs->prev = ls->fs; /* linked list of funcstates */
- fs->ls = ls;
- ls->fs = fs;
- fs->pc = 0;
- fs->previousline = f->linedefined;
- fs->iwthabs = 0;
- fs->lasttarget = 0;
- fs->freereg = 0;
- fs->nk = 0;
- fs->nabslineinfo = 0;
- fs->np = 0;
- fs->nups = 0;
- fs->ndebugvars = 0;
- fs->nactvar = 0;
- fs->needclose = 0;
- fs->firstlocal = ls->dyd->actvar.n;
- fs->firstlabel = ls->dyd->label.n;
- fs->bl = NULL;
- f->source = ls->source;
- luaC_objbarrier(L, f, f->source);
- f->maxstacksize = 2; /* registers 0/1 are always valid */
- fs->kcache = luaH_new(L); /* create table for function */
- sethvalue2s(L, L->top.p, fs->kcache); /* anchor it */
- luaD_inctop(L);
- enterblock(fs, bl, 0);
-}
-
-
-static void close_func (LexState *ls) {
- lua_State *L = ls->L;
- FuncState *fs = ls->fs;
- Proto *f = fs->f;
- luaK_ret(fs, luaY_nvarstack(fs), 0); /* final return */
- leaveblock(fs);
- lua_assert(fs->bl == NULL);
- luaK_finish(fs);
- luaM_shrinkvector(L, f->code, f->sizecode, fs->pc, Instruction);
- luaM_shrinkvector(L, f->lineinfo, f->sizelineinfo, fs->pc, ls_byte);
- luaM_shrinkvector(L, f->abslineinfo, f->sizeabslineinfo,
- fs->nabslineinfo, AbsLineInfo);
- luaM_shrinkvector(L, f->k, f->sizek, fs->nk, TValue);
- luaM_shrinkvector(L, f->p, f->sizep, fs->np, Proto *);
- luaM_shrinkvector(L, f->locvars, f->sizelocvars, fs->ndebugvars, LocVar);
- luaM_shrinkvector(L, f->upvalues, f->sizeupvalues, fs->nups, Upvaldesc);
- ls->fs = fs->prev;
- L->top.p--; /* pop kcache table */
- luaC_checkGC(L);
-}
-
-
-/*
-** {======================================================================
-** GRAMMAR RULES
-** =======================================================================
-*/
-
-
-/*
-** check whether current token is in the follow set of a block.
-** 'until' closes syntactical blocks, but do not close scope,
-** so it is handled in separate.
-*/
-static int block_follow (LexState *ls, int withuntil) {
- switch (ls->t.token) {
- case TK_ELSE: case TK_ELSEIF:
- case TK_END: case TK_EOS:
- return 1;
- case TK_UNTIL: return withuntil;
- default: return 0;
- }
-}
-
-
-static void statlist (LexState *ls) {
- /* statlist -> { stat [';'] } */
- while (!block_follow(ls, 1)) {
- if (ls->t.token == TK_RETURN) {
- statement(ls);
- return; /* 'return' must be last statement */
- }
- statement(ls);
- }
-}
-
-
-static void fieldsel (LexState *ls, expdesc *v) {
- /* fieldsel -> ['.' | ':'] NAME */
- FuncState *fs = ls->fs;
- expdesc key;
- luaK_exp2anyregup(fs, v);
- luaX_next(ls); /* skip the dot or colon */
- codename(ls, &key);
- luaK_indexed(fs, v, &key);
-}
-
-
-static void yindex (LexState *ls, expdesc *v) {
- /* index -> '[' expr ']' */
- luaX_next(ls); /* skip the '[' */
- expr(ls, v);
- luaK_exp2val(ls->fs, v);
- checknext(ls, ']');
-}
-
-
-/*
-** {======================================================================
-** Rules for Constructors
-** =======================================================================
-*/
-
-typedef struct ConsControl {
- expdesc v; /* last list item read */
- expdesc *t; /* table descriptor */
- int nh; /* total number of 'record' elements */
- int na; /* number of array elements already stored */
- int tostore; /* number of array elements pending to be stored */
- int maxtostore; /* maximum number of pending elements */
-} ConsControl;
-
-
-/*
-** Maximum number of elements in a constructor, to control the following:
-** * counter overflows;
-** * overflows in 'extra' for OP_NEWTABLE and OP_SETLIST;
-** * overflows when adding multiple returns in OP_SETLIST.
-*/
-#define MAX_CNST (INT_MAX/2)
-#if MAX_CNST/(MAXARG_vC + 1) > MAXARG_Ax
-#undef MAX_CNST
-#define MAX_CNST (MAXARG_Ax * (MAXARG_vC + 1))
-#endif
-
-
-static void recfield (LexState *ls, ConsControl *cc) {
- /* recfield -> (NAME | '['exp']') = exp */
- FuncState *fs = ls->fs;
- lu_byte reg = ls->fs->freereg;
- expdesc tab, key, val;
- if (ls->t.token == TK_NAME)
- codename(ls, &key);
- else /* ls->t.token == '[' */
- yindex(ls, &key);
- cc->nh++;
- checknext(ls, '=');
- tab = *cc->t;
- luaK_indexed(fs, &tab, &key);
- expr(ls, &val);
- luaK_storevar(fs, &tab, &val);
- fs->freereg = reg; /* free registers */
-}
-
-
-static void closelistfield (FuncState *fs, ConsControl *cc) {
- lua_assert(cc->tostore > 0);
- luaK_exp2nextreg(fs, &cc->v);
- cc->v.k = VVOID;
- if (cc->tostore >= cc->maxtostore) {
- luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore); /* flush */
- cc->na += cc->tostore;
- cc->tostore = 0; /* no more items pending */
- }
-}
-
-
-static void lastlistfield (FuncState *fs, ConsControl *cc) {
- if (cc->tostore == 0) return;
- if (hasmultret(cc->v.k)) {
- luaK_setmultret(fs, &cc->v);
- luaK_setlist(fs, cc->t->u.info, cc->na, LUA_MULTRET);
- cc->na--; /* do not count last expression (unknown number of elements) */
- }
- else {
- if (cc->v.k != VVOID)
- luaK_exp2nextreg(fs, &cc->v);
- luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore);
- }
- cc->na += cc->tostore;
-}
-
-
-static void listfield (LexState *ls, ConsControl *cc) {
- /* listfield -> exp */
- expr(ls, &cc->v);
- cc->tostore++;
-}
-
-
-static void field (LexState *ls, ConsControl *cc) {
- /* field -> listfield | recfield */
- switch(ls->t.token) {
- case TK_NAME: { /* may be 'listfield' or 'recfield' */
- if (luaX_lookahead(ls) != '=') /* expression? */
- listfield(ls, cc);
- else
- recfield(ls, cc);
- break;
- }
- case '[': {
- recfield(ls, cc);
- break;
- }
- default: {
- listfield(ls, cc);
- break;
- }
- }
-}
-
-
-/*
-** Compute a limit for how many registers a constructor can use before
-** emitting a 'SETLIST' instruction, based on how many registers are
-** available.
-*/
-static int maxtostore (FuncState *fs) {
- int numfreeregs = MAX_FSTACK - fs->freereg;
- if (numfreeregs >= 160) /* "lots" of registers? */
- return numfreeregs / 5; /* use up to 1/5 of them */
- else if (numfreeregs >= 80) /* still "enough" registers? */
- return 10; /* one 'SETLIST' instruction for each 10 values */
- else /* save registers for potential more nesting */
- return 1;
-}
-
-
-static void constructor (LexState *ls, expdesc *t) {
- /* constructor -> '{' [ field { sep field } [sep] ] '}'
- sep -> ',' | ';' */
- FuncState *fs = ls->fs;
- int line = ls->linenumber;
- int pc = luaK_codevABCk(fs, OP_NEWTABLE, 0, 0, 0, 0);
- ConsControl cc;
- luaK_code(fs, 0); /* space for extra arg. */
- cc.na = cc.nh = cc.tostore = 0;
- cc.t = t;
- init_exp(t, VNONRELOC, fs->freereg); /* table will be at stack top */
- luaK_reserveregs(fs, 1);
- init_exp(&cc.v, VVOID, 0); /* no value (yet) */
- checknext(ls, '{' /*}*/);
- cc.maxtostore = maxtostore(fs);
- do {
- if (ls->t.token == /*{*/ '}') break;
- if (cc.v.k != VVOID) /* is there a previous list item? */
- closelistfield(fs, &cc); /* close it */
- field(ls, &cc);
- luaY_checklimit(fs, cc.tostore + cc.na + cc.nh, MAX_CNST,
- "items in a constructor");
- } while (testnext(ls, ',') || testnext(ls, ';'));
- check_match(ls, /*{*/ '}', '{' /*}*/, line);
- lastlistfield(fs, &cc);
- luaK_settablesize(fs, pc, t->u.info, cc.na, cc.nh);
-}
-
-/* }====================================================================== */
-
-
-static void setvararg (FuncState *fs) {
- fs->f->flag |= PF_VAHID; /* by default, use hidden vararg arguments */
- luaK_codeABC(fs, OP_VARARGPREP, 0, 0, 0);
-}
-
-
-static void parlist (LexState *ls) {
- /* parlist -> [ {NAME ','} (NAME | '...') ] */
- FuncState *fs = ls->fs;
- Proto *f = fs->f;
- int nparams = 0;
- int varargk = 0;
- if (ls->t.token != ')') { /* is 'parlist' not empty? */
- do {
- switch (ls->t.token) {
- case TK_NAME: {
- new_localvar(ls, str_checkname(ls));
- nparams++;
- break;
- }
- case TK_DOTS: {
- varargk = 1;
- luaX_next(ls); /* skip '...' */
- if (ls->t.token == TK_NAME)
- new_varkind(ls, str_checkname(ls), RDKVAVAR);
- else
- new_localvarliteral(ls, "(vararg table)");
- break;
- }
- default: luaX_syntaxerror(ls, " or '...' expected");
- }
- } while (!varargk && testnext(ls, ','));
- }
- adjustlocalvars(ls, nparams);
- f->numparams = cast_byte(fs->nactvar);
- if (varargk) {
- setvararg(fs); /* declared vararg */
- adjustlocalvars(ls, 1); /* vararg parameter */
- }
- /* reserve registers for parameters (plus vararg parameter, if present) */
- luaK_reserveregs(fs, fs->nactvar);
-}
-
-
-static void body (LexState *ls, expdesc *e, int ismethod, int line) {
- /* body -> '(' parlist ')' block END */
- FuncState new_fs;
- BlockCnt bl;
- new_fs.f = addprototype(ls);
- new_fs.f->linedefined = line;
- open_func(ls, &new_fs, &bl);
- checknext(ls, '(');
- if (ismethod) {
- new_localvarliteral(ls, "self"); /* create 'self' parameter */
- adjustlocalvars(ls, 1);
- }
- parlist(ls);
- checknext(ls, ')');
- statlist(ls);
- new_fs.f->lastlinedefined = ls->linenumber;
- check_match(ls, TK_END, TK_FUNCTION, line);
- codeclosure(ls, e);
- close_func(ls);
-}
-
-
-static int explist (LexState *ls, expdesc *v) {
- /* explist -> expr { ',' expr } */
- int n = 1; /* at least one expression */
- expr(ls, v);
- while (testnext(ls, ',')) {
- luaK_exp2nextreg(ls->fs, v);
- expr(ls, v);
- n++;
- }
- return n;
-}
-
-
-static void funcargs (LexState *ls, expdesc *f) {
- FuncState *fs = ls->fs;
- expdesc args;
- int base, nparams;
- int line = ls->linenumber;
- switch (ls->t.token) {
- case '(': { /* funcargs -> '(' [ explist ] ')' */
- luaX_next(ls);
- if (ls->t.token == ')') /* arg list is empty? */
- args.k = VVOID;
- else {
- explist(ls, &args);
- if (hasmultret(args.k))
- luaK_setmultret(fs, &args);
- }
- check_match(ls, ')', '(', line);
- break;
- }
- case '{' /*}*/: { /* funcargs -> constructor */
- constructor(ls, &args);
- break;
- }
- case TK_STRING: { /* funcargs -> STRING */
- codestring(&args, ls->t.seminfo.ts);
- luaX_next(ls); /* must use 'seminfo' before 'next' */
- break;
- }
- default: {
- luaX_syntaxerror(ls, "function arguments expected");
- }
- }
- lua_assert(f->k == VNONRELOC);
- base = f->u.info; /* base register for call */
- if (hasmultret(args.k))
- nparams = LUA_MULTRET; /* open call */
- else {
- if (args.k != VVOID)
- luaK_exp2nextreg(fs, &args); /* close last argument */
- nparams = fs->freereg - (base+1);
- }
- init_exp(f, VCALL, luaK_codeABC(fs, OP_CALL, base, nparams+1, 2));
- luaK_fixline(fs, line);
- /* call removes function and arguments and leaves one result (unless
- changed later) */
- fs->freereg = cast_byte(base + 1);
-}
-
-
-
-
-/*
-** {======================================================================
-** Expression parsing
-** =======================================================================
-*/
-
-
-static void primaryexp (LexState *ls, expdesc *v) {
- /* primaryexp -> NAME | '(' expr ')' */
- switch (ls->t.token) {
- case '(': {
- int line = ls->linenumber;
- luaX_next(ls);
- expr(ls, v);
- check_match(ls, ')', '(', line);
- luaK_dischargevars(ls->fs, v);
- return;
- }
- case TK_NAME: {
- singlevar(ls, v);
- return;
- }
- default: {
- luaX_syntaxerror(ls, "unexpected symbol");
- }
- }
-}
-
-
-static void suffixedexp (LexState *ls, expdesc *v) {
- /* suffixedexp ->
- primaryexp { '.' NAME | '[' exp ']' | ':' NAME funcargs | funcargs } */
- FuncState *fs = ls->fs;
- primaryexp(ls, v);
- for (;;) {
- switch (ls->t.token) {
- case '.': { /* fieldsel */
- fieldsel(ls, v);
- break;
- }
- case '[': { /* '[' exp ']' */
- expdesc key;
- luaK_exp2anyregup(fs, v);
- yindex(ls, &key);
- luaK_indexed(fs, v, &key);
- break;
- }
- case ':': { /* ':' NAME funcargs */
- expdesc key;
- luaX_next(ls);
- codename(ls, &key);
- luaK_self(fs, v, &key);
- funcargs(ls, v);
- break;
- }
- case '(': case TK_STRING: case '{' /*}*/: { /* funcargs */
- luaK_exp2nextreg(fs, v);
- funcargs(ls, v);
- break;
- }
- default: return;
- }
- }
-}
-
-
-static void simpleexp (LexState *ls, expdesc *v) {
- /* simpleexp -> FLT | INT | STRING | NIL | TRUE | FALSE | ... |
- constructor | FUNCTION body | suffixedexp */
- switch (ls->t.token) {
- case TK_FLT: {
- init_exp(v, VKFLT, 0);
- v->u.nval = ls->t.seminfo.r;
- break;
- }
- case TK_INT: {
- init_exp(v, VKINT, 0);
- v->u.ival = ls->t.seminfo.i;
- break;
- }
- case TK_STRING: {
- codestring(v, ls->t.seminfo.ts);
- break;
- }
- case TK_NIL: {
- init_exp(v, VNIL, 0);
- break;
- }
- case TK_TRUE: {
- init_exp(v, VTRUE, 0);
- break;
- }
- case TK_FALSE: {
- init_exp(v, VFALSE, 0);
- break;
- }
- case TK_DOTS: { /* vararg */
- FuncState *fs = ls->fs;
- check_condition(ls, isvararg(fs->f),
- "cannot use '...' outside a vararg function");
- init_exp(v, VVARARG, luaK_codeABC(fs, OP_VARARG, 0, fs->f->numparams, 1));
- break;
- }
- case '{' /*}*/: { /* constructor */
- constructor(ls, v);
- return;
- }
- case TK_FUNCTION: {
- luaX_next(ls);
- body(ls, v, 0, ls->linenumber);
- return;
- }
- default: {
- suffixedexp(ls, v);
- return;
- }
- }
- luaX_next(ls);
-}
-
-
-static UnOpr getunopr (int op) {
- switch (op) {
- case TK_NOT: return OPR_NOT;
- case '-': return OPR_MINUS;
- case '~': return OPR_BNOT;
- case '#': return OPR_LEN;
- default: return OPR_NOUNOPR;
- }
-}
-
-
-static BinOpr getbinopr (int op) {
- switch (op) {
- case '+': return OPR_ADD;
- case '-': return OPR_SUB;
- case '*': return OPR_MUL;
- case '%': return OPR_MOD;
- case '^': return OPR_POW;
- case '/': return OPR_DIV;
- case TK_IDIV: return OPR_IDIV;
- case '&': return OPR_BAND;
- case '|': return OPR_BOR;
- case '~': return OPR_BXOR;
- case TK_SHL: return OPR_SHL;
- case TK_SHR: return OPR_SHR;
- case TK_CONCAT: return OPR_CONCAT;
- case TK_NE: return OPR_NE;
- case TK_EQ: return OPR_EQ;
- case '<': return OPR_LT;
- case TK_LE: return OPR_LE;
- case '>': return OPR_GT;
- case TK_GE: return OPR_GE;
- case TK_AND: return OPR_AND;
- case TK_OR: return OPR_OR;
- default: return OPR_NOBINOPR;
- }
-}
-
-
-/*
-** Priority table for binary operators.
-*/
-static const struct {
- lu_byte left; /* left priority for each binary operator */
- lu_byte right; /* right priority */
-} priority[] = { /* ORDER OPR */
- {10, 10}, {10, 10}, /* '+' '-' */
- {11, 11}, {11, 11}, /* '*' '%' */
- {14, 13}, /* '^' (right associative) */
- {11, 11}, {11, 11}, /* '/' '//' */
- {6, 6}, {4, 4}, {5, 5}, /* '&' '|' '~' */
- {7, 7}, {7, 7}, /* '<<' '>>' */
- {9, 8}, /* '..' (right associative) */
- {3, 3}, {3, 3}, {3, 3}, /* ==, <, <= */
- {3, 3}, {3, 3}, {3, 3}, /* ~=, >, >= */
- {2, 2}, {1, 1} /* and, or */
-};
-
-#define UNARY_PRIORITY 12 /* priority for unary operators */
-
-
-/*
-** subexpr -> (simpleexp | unop subexpr) { binop subexpr }
-** where 'binop' is any binary operator with a priority higher than 'limit'
-*/
-static BinOpr subexpr (LexState *ls, expdesc *v, int limit) {
- BinOpr op;
- UnOpr uop;
- enterlevel(ls);
- uop = getunopr(ls->t.token);
- if (uop != OPR_NOUNOPR) { /* prefix (unary) operator? */
- int line = ls->linenumber;
- luaX_next(ls); /* skip operator */
- subexpr(ls, v, UNARY_PRIORITY);
- luaK_prefix(ls->fs, uop, v, line);
- }
- else simpleexp(ls, v);
- /* expand while operators have priorities higher than 'limit' */
- op = getbinopr(ls->t.token);
- while (op != OPR_NOBINOPR && priority[op].left > limit) {
- expdesc v2;
- BinOpr nextop;
- int line = ls->linenumber;
- luaX_next(ls); /* skip operator */
- luaK_infix(ls->fs, op, v);
- /* read sub-expression with higher priority */
- nextop = subexpr(ls, &v2, priority[op].right);
- luaK_posfix(ls->fs, op, v, &v2, line);
- op = nextop;
- }
- leavelevel(ls);
- return op; /* return first untreated operator */
-}
-
-
-static void expr (LexState *ls, expdesc *v) {
- subexpr(ls, v, 0);
-}
-
-/* }==================================================================== */
-
-
-
-/*
-** {======================================================================
-** Rules for Statements
-** =======================================================================
-*/
-
-
-static void block (LexState *ls) {
- /* block -> statlist */
- FuncState *fs = ls->fs;
- BlockCnt bl;
- enterblock(fs, &bl, 0);
- statlist(ls);
- leaveblock(fs);
-}
-
-
-/*
-** structure to chain all variables in the left-hand side of an
-** assignment
-*/
-struct LHS_assign {
- struct LHS_assign *prev;
- expdesc v; /* variable (global, local, upvalue, or indexed) */
-};
-
-
-/*
-** check whether, in an assignment to an upvalue/local variable, the
-** upvalue/local variable is begin used in a previous assignment to a
-** table. If so, save original upvalue/local value in a safe place and
-** use this safe copy in the previous assignment.
-*/
-static void check_conflict (LexState *ls, struct LHS_assign *lh, expdesc *v) {
- FuncState *fs = ls->fs;
- lu_byte extra = fs->freereg; /* eventual position to save local variable */
- int conflict = 0;
- for (; lh; lh = lh->prev) { /* check all previous assignments */
- if (vkisindexed(lh->v.k)) { /* assignment to table field? */
- if (lh->v.k == VINDEXUP) { /* is table an upvalue? */
- if (v->k == VUPVAL && lh->v.u.ind.t == v->u.info) {
- conflict = 1; /* table is the upvalue being assigned now */
- lh->v.k = VINDEXSTR;
- lh->v.u.ind.t = extra; /* assignment will use safe copy */
- }
- }
- else { /* table is a register */
- if (v->k == VLOCAL && lh->v.u.ind.t == v->u.var.ridx) {
- conflict = 1; /* table is the local being assigned now */
- lh->v.u.ind.t = extra; /* assignment will use safe copy */
- }
- /* is index the local being assigned? */
- if (lh->v.k == VINDEXED && v->k == VLOCAL &&
- lh->v.u.ind.idx == v->u.var.ridx) {
- conflict = 1;
- lh->v.u.ind.idx = extra; /* previous assignment will use safe copy */
- }
- }
- }
- }
- if (conflict) {
- /* copy upvalue/local value to a temporary (in position 'extra') */
- if (v->k == VLOCAL)
- luaK_codeABC(fs, OP_MOVE, extra, v->u.var.ridx, 0);
- else
- luaK_codeABC(fs, OP_GETUPVAL, extra, v->u.info, 0);
- luaK_reserveregs(fs, 1);
- }
-}
-
-
-/* Create code to store the "top" register in 'var' */
-static void storevartop (FuncState *fs, expdesc *var) {
- expdesc e;
- init_exp(&e, VNONRELOC, fs->freereg - 1);
- luaK_storevar(fs, var, &e); /* will also free the top register */
-}
-
-
-/*
-** Parse and compile a multiple assignment. The first "variable"
-** (a 'suffixedexp') was already read by the caller.
-**
-** assignment -> suffixedexp restassign
-** restassign -> ',' suffixedexp restassign | '=' explist
-*/
-static void restassign (LexState *ls, struct LHS_assign *lh, int nvars) {
- expdesc e;
- check_condition(ls, vkisvar(lh->v.k), "syntax error");
- check_readonly(ls, &lh->v);
- if (testnext(ls, ',')) { /* restassign -> ',' suffixedexp restassign */
- struct LHS_assign nv;
- nv.prev = lh;
- suffixedexp(ls, &nv.v);
- if (!vkisindexed(nv.v.k))
- check_conflict(ls, lh, &nv.v);
- enterlevel(ls); /* control recursion depth */
- restassign(ls, &nv, nvars+1);
- leavelevel(ls);
- }
- else { /* restassign -> '=' explist */
- int nexps;
- checknext(ls, '=');
- nexps = explist(ls, &e);
- if (nexps != nvars)
- adjust_assign(ls, nvars, nexps, &e);
- else {
- luaK_setoneret(ls->fs, &e); /* close last expression */
- luaK_storevar(ls->fs, &lh->v, &e);
- return; /* avoid default */
- }
- }
- storevartop(ls->fs, &lh->v); /* default assignment */
-}
-
-
-static int cond (LexState *ls) {
- /* cond -> exp */
- expdesc v;
- expr(ls, &v); /* read condition */
- if (v.k == VNIL) v.k = VFALSE; /* 'falses' are all equal here */
- luaK_goiftrue(ls->fs, &v);
- return v.f;
-}
-
-
-static void gotostat (LexState *ls, int line) {
- TString *name = str_checkname(ls); /* label's name */
- newgotoentry(ls, name, line);
-}
-
-
-/*
-** Break statement. Semantically equivalent to "goto break".
-*/
-static void breakstat (LexState *ls, int line) {
- BlockCnt *bl; /* to look for an enclosing loop */
- for (bl = ls->fs->bl; bl != NULL; bl = bl->previous) {
- if (bl->isloop) /* found one? */
- goto ok;
- }
- luaX_syntaxerror(ls, "break outside loop");
- ok:
- bl->isloop = 2; /* signal that block has pending breaks */
- luaX_next(ls); /* skip break */
- newgotoentry(ls, ls->brkn, line);
-}
-
-
-/*
-** Check whether there is already a label with the given 'name' at
-** current function.
-*/
-static void checkrepeated (LexState *ls, TString *name) {
- Labeldesc *lb = findlabel(ls, name, ls->fs->firstlabel);
- if (l_unlikely(lb != NULL)) /* already defined? */
- luaK_semerror(ls, "label '%s' already defined on line %d",
- getstr(name), lb->line); /* error */
-}
-
-
-static void labelstat (LexState *ls, TString *name, int line) {
- /* label -> '::' NAME '::' */
- checknext(ls, TK_DBCOLON); /* skip double colon */
- while (ls->t.token == ';' || ls->t.token == TK_DBCOLON)
- statement(ls); /* skip other no-op statements */
- checkrepeated(ls, name); /* check for repeated labels */
- createlabel(ls, name, line, block_follow(ls, 0));
-}
-
-
-static void whilestat (LexState *ls, int line) {
- /* whilestat -> WHILE cond DO block END */
- FuncState *fs = ls->fs;
- int whileinit;
- int condexit;
- BlockCnt bl;
- luaX_next(ls); /* skip WHILE */
- whileinit = luaK_getlabel(fs);
- condexit = cond(ls);
- enterblock(fs, &bl, 1);
- checknext(ls, TK_DO);
- block(ls);
- luaK_jumpto(fs, whileinit);
- check_match(ls, TK_END, TK_WHILE, line);
- leaveblock(fs);
- 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);
- BlockCnt bl1, bl2;
- enterblock(fs, &bl1, 1); /* loop block */
- enterblock(fs, &bl2, 0); /* scope block */
- luaX_next(ls); /* skip REPEAT */
- statlist(ls);
- check_match(ls, TK_UNTIL, TK_REPEAT, line);
- condexit = cond(ls); /* read condition (inside scope block) */
- leaveblock(fs); /* finish scope */
- if (bl2.upval) { /* upvalues? */
- int exit = luaK_jump(fs); /* normal exit must jump over fix */
- luaK_patchtohere(fs, condexit); /* repetition must close upvalues */
- luaK_codeABC(fs, OP_CLOSE, reglevel(fs, bl2.nactvar), 0, 0);
- condexit = luaK_jump(fs); /* repeat after closing upvalues */
- luaK_patchtohere(fs, exit); /* normal exit comes to here */
- }
- luaK_patchlist(fs, condexit, repeat_init); /* close the loop */
- leaveblock(fs); /* finish loop */
-}
-
-
-/*
-** Read an expression and generate code to put its results in next
-** stack slot.
-**
-*/
-static void exp1 (LexState *ls) {
- expdesc e;
- expr(ls, &e);
- luaK_exp2nextreg(ls->fs, &e);
- lua_assert(e.k == VNONRELOC);
-}
-
-
-/*
-** Fix for instruction at position 'pc' to jump to 'dest'.
-** (Jump addresses are relative in Lua). 'back' true means
-** a back jump.
-*/
-static void fixforjump (FuncState *fs, int pc, int dest, int back) {
- Instruction *jmp = &fs->f->code[pc];
- int offset = dest - (pc + 1);
- if (back)
- offset = -offset;
- if (l_unlikely(offset > MAXARG_Bx))
- luaX_syntaxerror(fs->ls, "control structure too long");
- SETARG_Bx(*jmp, offset);
-}
-
-
-/*
-** Generate code for a 'for' loop.
-*/
-static void forbody (LexState *ls, int base, int line, int nvars, int isgen) {
- /* forbody -> DO block */
- static const OpCode forprep[2] = {OP_FORPREP, OP_TFORPREP};
- static const OpCode forloop[2] = {OP_FORLOOP, OP_TFORLOOP};
- BlockCnt bl;
- FuncState *fs = ls->fs;
- int prep, endfor;
- checknext(ls, TK_DO);
- prep = luaK_codeABx(fs, forprep[isgen], base, 0);
- fs->freereg--; /* both 'forprep' remove one register from the stack */
- enterblock(fs, &bl, 0); /* scope for declared variables */
- adjustlocalvars(ls, nvars);
- luaK_reserveregs(fs, nvars);
- block(ls);
- leaveblock(fs); /* end of scope for declared variables */
- fixforjump(fs, prep, luaK_getlabel(fs), 0);
- if (isgen) { /* generic for? */
- luaK_codeABC(fs, OP_TFORCALL, base, 0, nvars);
- luaK_fixline(fs, line);
- }
- endfor = luaK_codeABx(fs, forloop[isgen], base, 0);
- fixforjump(fs, endfor, prep + 1, 1);
- luaK_fixline(fs, line);
-}
-
-
-/*
-** Control whether for-loop control variables are read-only
-*/
-#if LUA_COMPAT_LOOPVAR
-#define LOOPVARKIND VDKREG
-#else /* by default, these variables are read only */
-#define LOOPVARKIND RDKCONST
-#endif
-
-static void fornum (LexState *ls, TString *varname, int line) {
- /* fornum -> NAME = exp,exp[,exp] forbody */
- FuncState *fs = ls->fs;
- int base = fs->freereg;
- new_localvarliteral(ls, "(for state)");
- new_localvarliteral(ls, "(for state)");
- new_varkind(ls, varname, LOOPVARKIND); /* control variable */
- checknext(ls, '=');
- exp1(ls); /* initial value */
- checknext(ls, ',');
- exp1(ls); /* limit */
- if (testnext(ls, ','))
- exp1(ls); /* optional step */
- else { /* default step = 1 */
- luaK_int(fs, fs->freereg, 1);
- luaK_reserveregs(fs, 1);
- }
- adjustlocalvars(ls, 2); /* start scope for internal variables */
- forbody(ls, base, line, 1, 0);
-}
-
-
-static void forlist (LexState *ls, TString *indexname) {
- /* forlist -> NAME {,NAME} IN explist forbody */
- FuncState *fs = ls->fs;
- expdesc e;
- int nvars = 4; /* function, state, closing, control */
- int line;
- int base = fs->freereg;
- /* create internal variables */
- new_localvarliteral(ls, "(for state)"); /* iterator function */
- new_localvarliteral(ls, "(for state)"); /* state */
- new_localvarliteral(ls, "(for state)"); /* closing var. (after swap) */
- new_varkind(ls, indexname, LOOPVARKIND); /* control variable */
- /* other declared variables */
- while (testnext(ls, ',')) {
- new_localvar(ls, str_checkname(ls));
- nvars++;
- }
- checknext(ls, TK_IN);
- line = ls->linenumber;
- adjust_assign(ls, 4, explist(ls, &e), &e);
- adjustlocalvars(ls, 3); /* start scope for internal variables */
- marktobeclosed(fs); /* last internal var. must be closed */
- luaK_checkstack(fs, 2); /* extra space to call iterator */
- forbody(ls, base, line, nvars - 3, 1);
-}
-
-
-static void forstat (LexState *ls, int line) {
- /* forstat -> FOR (fornum | forlist) END */
- FuncState *fs = ls->fs;
- TString *varname;
- BlockCnt bl;
- enterblock(fs, &bl, 1); /* scope for loop and control variables */
- luaX_next(ls); /* skip 'for' */
- varname = str_checkname(ls); /* first variable name */
- switch (ls->t.token) {
- case '=': fornum(ls, varname, line); break;
- case ',': case TK_IN: forlist(ls, varname); break;
- default: luaX_syntaxerror(ls, "'=' or 'in' expected");
- }
- check_match(ls, TK_END, TK_FOR, line);
- leaveblock(fs); /* loop scope ('break' jumps to this point) */
-}
-
-
-static void test_then_block (LexState *ls, int *escapelist) {
- /* test_then_block -> [IF | ELSEIF] cond THEN block */
- FuncState *fs = ls->fs;
- int condtrue;
- luaX_next(ls); /* skip IF or ELSEIF */
- condtrue = cond(ls); /* read condition */
- checknext(ls, TK_THEN);
- block(ls); /* 'then' part */
- if (ls->t.token == TK_ELSE ||
- ls->t.token == TK_ELSEIF) /* followed by 'else'/'elseif'? */
- luaK_concat(fs, escapelist, luaK_jump(fs)); /* must jump over it */
- luaK_patchtohere(fs, condtrue);
-}
-
-
-static void ifstat (LexState *ls, int line) {
- /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */
- FuncState *fs = ls->fs;
- int escapelist = NO_JUMP; /* exit list for finished parts */
- test_then_block(ls, &escapelist); /* IF cond THEN block */
- while (ls->t.token == TK_ELSEIF)
- test_then_block(ls, &escapelist); /* ELSEIF cond THEN block */
- if (testnext(ls, TK_ELSE))
- block(ls); /* 'else' part */
- check_match(ls, TK_END, TK_IF, line);
- luaK_patchtohere(fs, escapelist); /* patch escape list to 'if' end */
-}
-
-
-static void localfunc (LexState *ls) {
- expdesc b;
- FuncState *fs = ls->fs;
- int fvar = fs->nactvar; /* function's variable index */
- new_localvar(ls, str_checkname(ls)); /* new local variable */
- adjustlocalvars(ls, 1); /* enter its scope */
- body(ls, &b, 0, ls->linenumber); /* function created in next register */
- /* debug information will only see the variable after this point! */
- localdebuginfo(fs, fvar)->startpc = fs->pc;
-}
-
-
-static lu_byte getvarattribute (LexState *ls, lu_byte df) {
- /* attrib -> ['<' NAME '>'] */
- if (testnext(ls, '<')) {
- TString *ts = str_checkname(ls);
- const char *attr = getstr(ts);
- checknext(ls, '>');
- if (strcmp(attr, "const") == 0)
- return RDKCONST; /* read-only variable */
- else if (strcmp(attr, "close") == 0)
- return RDKTOCLOSE; /* to-be-closed variable */
- else
- luaK_semerror(ls, "unknown attribute '%s'", attr);
- }
- return df; /* return default value */
-}
-
-
-static void checktoclose (FuncState *fs, int level) {
- if (level != -1) { /* is there a to-be-closed variable? */
- marktobeclosed(fs);
- luaK_codeABC(fs, OP_TBC, reglevel(fs, level), 0, 0);
- }
-}
-
-
-static void localstat (LexState *ls) {
- /* stat -> LOCAL NAME attrib { ',' NAME attrib } ['=' explist] */
- FuncState *fs = ls->fs;
- int toclose = -1; /* index of to-be-closed variable (if any) */
- Vardesc *var; /* last variable */
- int vidx; /* index of last variable */
- int nvars = 0;
- int nexps;
- expdesc e;
- /* get prefixed attribute (if any); default is regular local variable */
- lu_byte defkind = getvarattribute(ls, VDKREG);
- do { /* for each variable */
- TString *vname = str_checkname(ls); /* get its name */
- lu_byte kind = getvarattribute(ls, defkind); /* postfixed attribute */
- vidx = new_varkind(ls, vname, kind); /* predeclare it */
- if (kind == RDKTOCLOSE) { /* to-be-closed? */
- if (toclose != -1) /* one already present? */
- luaK_semerror(ls, "multiple to-be-closed variables in local list");
- toclose = fs->nactvar + nvars;
- }
- nvars++;
- } while (testnext(ls, ','));
- if (testnext(ls, '=')) /* initialization? */
- nexps = explist(ls, &e);
- else {
- e.k = VVOID;
- nexps = 0;
- }
- var = getlocalvardesc(fs, vidx); /* retrieve last variable */
- if (nvars == nexps && /* no adjustments? */
- var->vd.kind == RDKCONST && /* last variable is const? */
- luaK_exp2const(fs, &e, &var->k)) { /* compile-time constant? */
- var->vd.kind = RDKCTC; /* variable is a compile-time constant */
- adjustlocalvars(ls, nvars - 1); /* exclude last variable */
- fs->nactvar++; /* but count it */
- }
- else {
- adjust_assign(ls, nvars, nexps, &e);
- adjustlocalvars(ls, nvars);
- }
- checktoclose(fs, toclose);
-}
-
-
-static lu_byte getglobalattribute (LexState *ls, lu_byte df) {
- lu_byte kind = getvarattribute(ls, df);
- switch (kind) {
- case RDKTOCLOSE:
- luaK_semerror(ls, "global variables cannot be to-be-closed");
- return kind; /* to avoid warnings */
- case RDKCONST:
- return GDKCONST; /* adjust kind for global variable */
- default:
- return kind;
- }
-}
-
-
-static void checkglobal (LexState *ls, TString *varname, int line) {
- FuncState *fs = ls->fs;
- expdesc var;
- int k;
- buildglobal(ls, varname, &var); /* create global variable in 'var' */
- k = var.u.ind.keystr; /* index of global name in 'k' */
- luaK_codecheckglobal(fs, &var, k, line);
-}
-
-
-/*
-** Recursively traverse list of globals to be initalized. When
-** going, generate table description for the global. In the end,
-** after all indices have been generated, read list of initializing
-** expressions. When returning, generate the assignment of the value on
-** the stack to the corresponding table description. 'n' is the variable
-** being handled, range [0, nvars - 1].
-*/
-static void initglobal (LexState *ls, int nvars, int firstidx, int n,
- int line) {
- if (n == nvars) { /* traversed all variables? */
- expdesc e;
- int nexps = explist(ls, &e); /* read list of expressions */
- adjust_assign(ls, nvars, nexps, &e);
- }
- else { /* handle variable 'n' */
- FuncState *fs = ls->fs;
- expdesc var;
- TString *varname = getlocalvardesc(fs, firstidx + n)->vd.name;
- buildglobal(ls, varname, &var); /* create global variable in 'var' */
- enterlevel(ls); /* control recursion depth */
- initglobal(ls, nvars, firstidx, n + 1, line);
- leavelevel(ls);
- checkglobal(ls, varname, line);
- storevartop(fs, &var);
- }
-}
-
-
-static void globalnames (LexState *ls, lu_byte defkind) {
- FuncState *fs = ls->fs;
- int nvars = 0;
- int lastidx; /* index of last registered variable */
- do { /* for each name */
- TString *vname = str_checkname(ls);
- lu_byte kind = getglobalattribute(ls, defkind);
- lastidx = new_varkind(ls, vname, kind);
- nvars++;
- } while (testnext(ls, ','));
- if (testnext(ls, '=')) /* initialization? */
- initglobal(ls, nvars, lastidx - nvars + 1, 0, ls->linenumber);
- fs->nactvar = cast_short(fs->nactvar + nvars); /* activate declaration */
-}
-
-
-static void globalstat (LexState *ls) {
- /* globalstat -> (GLOBAL) attrib '*'
- globalstat -> (GLOBAL) attrib NAME attrib {',' NAME attrib} */
- FuncState *fs = ls->fs;
- /* get prefixed attribute (if any); default is regular global variable */
- lu_byte defkind = getglobalattribute(ls, GDKREG);
- if (!testnext(ls, '*'))
- globalnames(ls, defkind);
- else {
- /* use NULL as name to represent '*' entries */
- new_varkind(ls, NULL, defkind);
- fs->nactvar++; /* activate declaration */
- }
-}
-
-
-static void globalfunc (LexState *ls, int line) {
- /* globalfunc -> (GLOBAL FUNCTION) NAME body */
- expdesc var, b;
- FuncState *fs = ls->fs;
- TString *fname = str_checkname(ls);
- new_varkind(ls, fname, GDKREG); /* declare global variable */
- fs->nactvar++; /* enter its scope */
- buildglobal(ls, fname, &var);
- body(ls, &b, 0, ls->linenumber); /* compile and return closure in 'b' */
- checkglobal(ls, fname, line);
- luaK_storevar(fs, &var, &b);
- luaK_fixline(fs, line); /* definition "happens" in the first line */
-}
-
-
-static void globalstatfunc (LexState *ls, int line) {
- /* stat -> GLOBAL globalfunc | GLOBAL globalstat */
- luaX_next(ls); /* skip 'global' */
- if (testnext(ls, TK_FUNCTION))
- globalfunc(ls, line);
- else
- globalstat(ls);
-}
-
-
-static int funcname (LexState *ls, expdesc *v) {
- /* funcname -> NAME {fieldsel} [':' NAME] */
- int ismethod = 0;
- singlevar(ls, v);
- while (ls->t.token == '.')
- fieldsel(ls, v);
- if (ls->t.token == ':') {
- ismethod = 1;
- fieldsel(ls, v);
- }
- return ismethod;
-}
-
-
-static void funcstat (LexState *ls, int line) {
- /* funcstat -> FUNCTION funcname body */
- int ismethod;
- expdesc v, b;
- luaX_next(ls); /* skip FUNCTION */
- ismethod = funcname(ls, &v);
- check_readonly(ls, &v);
- body(ls, &b, ismethod, line);
- luaK_storevar(ls->fs, &v, &b);
- luaK_fixline(ls->fs, line); /* definition "happens" in the first line */
-}
-
-
-static void exprstat (LexState *ls) {
- /* stat -> func | assignment */
- FuncState *fs = ls->fs;
- struct LHS_assign v;
- suffixedexp(ls, &v.v);
- if (ls->t.token == '=' || ls->t.token == ',') { /* stat -> assignment ? */
- v.prev = NULL;
- restassign(ls, &v, 1);
- }
- else { /* stat -> func */
- Instruction *inst;
- check_condition(ls, v.v.k == VCALL, "syntax error");
- inst = &getinstruction(fs, &v.v);
- SETARG_C(*inst, 1); /* call statement uses no results */
- }
-}
-
-
-static void retstat (LexState *ls) {
- /* stat -> RETURN [explist] [';'] */
- FuncState *fs = ls->fs;
- expdesc e;
- int nret; /* number of values being returned */
- int first = luaY_nvarstack(fs); /* first slot to be returned */
- if (block_follow(ls, 1) || ls->t.token == ';')
- nret = 0; /* return no values */
- else {
- nret = explist(ls, &e); /* optional return values */
- if (hasmultret(e.k)) {
- luaK_setmultret(fs, &e);
- if (e.k == VCALL && nret == 1 && !fs->bl->insidetbc) { /* tail call? */
- SET_OPCODE(getinstruction(fs,&e), OP_TAILCALL);
- lua_assert(GETARG_A(getinstruction(fs,&e)) == luaY_nvarstack(fs));
- }
- nret = LUA_MULTRET; /* return all values */
- }
- else {
- if (nret == 1) /* only one single value? */
- first = luaK_exp2anyreg(fs, &e); /* can use original slot */
- else { /* values must go to the top of the stack */
- luaK_exp2nextreg(fs, &e);
- lua_assert(nret == fs->freereg - first);
- }
- }
- }
- luaK_ret(fs, first, nret);
- testnext(ls, ';'); /* skip optional semicolon */
-}
-
-
-static void statement (LexState *ls) {
- int line = ls->linenumber; /* may be needed for error messages */
- enterlevel(ls);
- switch (ls->t.token) {
- case ';': { /* stat -> ';' (empty statement) */
- luaX_next(ls); /* skip ';' */
- break;
- }
- case TK_IF: { /* stat -> ifstat */
- ifstat(ls, line);
- break;
- }
- case TK_WHILE: { /* stat -> whilestat */
- whilestat(ls, line);
- break;
- }
- case TK_DO: { /* stat -> DO block END */
- luaX_next(ls); /* skip DO */
- block(ls);
- check_match(ls, TK_END, TK_DO, line);
- break;
- }
- case TK_FOR: { /* stat -> forstat */
- forstat(ls, line);
- break;
- }
- case TK_REPEAT: { /* stat -> repeatstat */
- repeatstat(ls, line);
- break;
- }
- case TK_FUNCTION: { /* stat -> funcstat */
- funcstat(ls, line);
- break;
- }
- case TK_LOCAL: { /* stat -> localstat */
- luaX_next(ls); /* skip LOCAL */
- if (testnext(ls, TK_FUNCTION)) /* local function? */
- localfunc(ls);
- else
- localstat(ls);
- break;
- }
- case TK_GLOBAL: { /* stat -> globalstatfunc */
- globalstatfunc(ls, line);
- break;
- }
- case TK_DBCOLON: { /* stat -> label */
- luaX_next(ls); /* skip double colon */
- labelstat(ls, str_checkname(ls), line);
- break;
- }
- case TK_RETURN: { /* stat -> retstat */
- luaX_next(ls); /* skip RETURN */
- retstat(ls);
- break;
- }
- case TK_BREAK: { /* stat -> breakstat */
- breakstat(ls, line);
- break;
- }
- case TK_GOTO: { /* stat -> 'goto' NAME */
- luaX_next(ls); /* skip 'goto' */
- gotostat(ls, line);
- break;
- }
-#if LUA_COMPAT_GLOBAL
- case TK_NAME: {
- /* compatibility code to parse global keyword when "global"
- is not reserved */
- if (ls->t.seminfo.ts == ls->glbn) { /* current = "global"? */
- int lk = luaX_lookahead(ls);
- if (lk == '<' || lk == TK_NAME || lk == '*' || lk == TK_FUNCTION) {
- /* 'global ' or 'global name' or 'global *' or
- 'global function' */
- globalstatfunc(ls, line);
- break;
- }
- } /* else... */
- }
-#endif
- /* FALLTHROUGH */
- default: { /* stat -> func | assignment */
- exprstat(ls);
- break;
- }
- }
- lua_assert(ls->fs->f->maxstacksize >= ls->fs->freereg &&
- ls->fs->freereg >= luaY_nvarstack(ls->fs));
- ls->fs->freereg = luaY_nvarstack(ls->fs); /* free registers */
- leavelevel(ls);
-}
-
-/* }====================================================================== */
-
-/* }====================================================================== */
-
-
-/*
-** compiles the main function, which is a regular vararg function with an
-** upvalue named LUA_ENV
-*/
-static void mainfunc (LexState *ls, FuncState *fs) {
- BlockCnt bl;
- Upvaldesc *env;
- open_func(ls, fs, &bl);
- setvararg(fs); /* main function is always vararg */
- env = allocupvalue(fs); /* ...set environment upvalue */
- env->instack = 1;
- env->idx = 0;
- env->kind = VDKREG;
- env->name = ls->envn;
- luaC_objbarrier(ls->L, fs->f, env->name);
- luaX_next(ls); /* read first token */
- statlist(ls); /* parse main body */
- check(ls, TK_EOS);
- close_func(ls);
-}
-
-
-LClosure *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff,
- Dyndata *dyd, const char *name, int firstchar) {
- LexState lexstate;
- FuncState funcstate;
- LClosure *cl = luaF_newLclosure(L, 1); /* create main closure */
- setclLvalue2s(L, L->top.p, cl); /* anchor it (to avoid being collected) */
- luaD_inctop(L);
- lexstate.h = luaH_new(L); /* create table for scanner */
- sethvalue2s(L, L->top.p, lexstate.h); /* anchor it */
- luaD_inctop(L);
- funcstate.f = cl->p = luaF_newproto(L);
- luaC_objbarrier(L, cl, cl->p);
- funcstate.f->source = luaS_new(L, name); /* create and anchor TString */
- luaC_objbarrier(L, funcstate.f, funcstate.f->source);
- lexstate.buff = buff;
- lexstate.dyd = dyd;
- dyd->actvar.n = dyd->gt.n = dyd->label.n = 0;
- luaX_setinput(L, &lexstate, z, funcstate.f->source, firstchar);
- mainfunc(&lexstate, &funcstate);
- lua_assert(!funcstate.prev && funcstate.nups == 1 && !lexstate.fs);
- /* all scopes should be correctly finished */
- lua_assert(dyd->actvar.n == 0 && dyd->gt.n == 0 && dyd->label.n == 0);
- L->top.p--; /* remove scanner's table */
- return cl; /* closure is on the stack, too */
-}
-
diff --git a/lparser.h b/lparser.h
deleted file mode 100644
index a30df04f77..0000000000
--- a/lparser.h
+++ /dev/null
@@ -1,196 +0,0 @@
-/*
-** $Id: lparser.h $
-** Lua Parser
-** See Copyright Notice in lua.h
-*/
-
-#ifndef lparser_h
-#define lparser_h
-
-#include "llimits.h"
-#include "lobject.h"
-#include "lzio.h"
-
-
-/*
-** Expression and variable descriptor.
-** Code generation for variables and expressions can be delayed to allow
-** optimizations; An 'expdesc' structure describes a potentially-delayed
-** variable/expression. It has a description of its "main" value plus a
-** list of conditional jumps that can also produce its value (generated
-** by short-circuit operators 'and'/'or').
-*/
-
-/* kinds of variables/expressions */
-typedef enum {
- VVOID, /* when 'expdesc' describes the last expression of a list,
- this kind means an empty list (so, no expression) */
- VNIL, /* constant nil */
- VTRUE, /* constant true */
- VFALSE, /* constant false */
- VK, /* constant in 'k'; info = index of constant in 'k' */
- VKFLT, /* floating constant; nval = numerical float value */
- VKINT, /* integer constant; ival = numerical integer value */
- VKSTR, /* string constant; strval = TString address;
- (string is fixed by the scanner) */
- VNONRELOC, /* expression has its value in a fixed register;
- info = result register */
- VLOCAL, /* local variable; var.ridx = register index;
- var.vidx = relative index in 'actvar.arr' */
- VVARGVAR, /* vararg parameter; var.ridx = register index;
- var.vidx = relative index in 'actvar.arr' */
- VGLOBAL, /* global variable;
- info = relative index in 'actvar.arr' (or -1 for
- implicit declaration) */
- VUPVAL, /* upvalue variable; info = index of upvalue in 'upvalues' */
- VCONST, /* compile-time variable;
- info = absolute index in 'actvar.arr' */
- VINDEXED, /* indexed variable;
- ind.t = table register;
- ind.idx = key's R index;
- ind.ro = true if it represents a read-only global;
- ind.keystr = if key is a string, index in 'k' of that string;
- -1 if key is not a string */
- VVARGIND, /* indexed vararg parameter;
- ind.* as in VINDEXED */
- VINDEXUP, /* indexed upvalue;
- ind.idx = key's K index;
- ind.* as in VINDEXED */
- VINDEXI, /* indexed variable with constant integer;
- ind.t = table register;
- ind.idx = key's value */
- VINDEXSTR, /* indexed variable with literal string;
- ind.idx = key's K index;
- ind.* as in VINDEXED */
- VJMP, /* expression is a test/comparison;
- info = pc of corresponding jump instruction */
- VRELOC, /* expression can put result in any register;
- info = instruction pc */
- VCALL, /* expression is a function call; info = instruction pc */
- VVARARG /* vararg expression; info = instruction pc */
-} expkind;
-
-
-#define vkisvar(k) (VLOCAL <= (k) && (k) <= VINDEXSTR)
-#define vkisindexed(k) (VINDEXED <= (k) && (k) <= VINDEXSTR)
-
-
-typedef struct expdesc {
- expkind k;
- union {
- lua_Integer ival; /* for VKINT */
- lua_Number nval; /* for VKFLT */
- TString *strval; /* for VKSTR */
- int info; /* for generic use */
- struct { /* for indexed variables */
- short idx; /* index (R or "long" K) */
- lu_byte t; /* table (register or upvalue) */
- lu_byte ro; /* true if variable is read-only */
- int keystr; /* index in 'k' of string key, or -1 if not a string */
- } ind;
- struct { /* for local variables */
- lu_byte ridx; /* register holding the variable */
- short vidx; /* index in 'actvar.arr' */
- } var;
- } u;
- int t; /* patch list of 'exit when true' */
- int f; /* patch list of 'exit when false' */
-} expdesc;
-
-
-/* kinds of variables */
-#define VDKREG 0 /* regular local */
-#define RDKCONST 1 /* local constant */
-#define RDKVAVAR 2 /* vararg parameter */
-#define RDKTOCLOSE 3 /* to-be-closed */
-#define RDKCTC 4 /* local compile-time constant */
-#define GDKREG 5 /* regular global */
-#define GDKCONST 6 /* global constant */
-
-/* variables that live in registers */
-#define varinreg(v) ((v)->vd.kind <= RDKTOCLOSE)
-
-/* test for global variables */
-#define varglobal(v) ((v)->vd.kind >= GDKREG)
-
-
-/* description of an active variable */
-typedef union Vardesc {
- struct {
- TValuefields; /* constant value (if it is a compile-time constant) */
- lu_byte kind;
- lu_byte ridx; /* register holding the variable */
- short pidx; /* index of the variable in the Proto's 'locvars' array */
- TString *name; /* variable name */
- } vd;
- TValue k; /* constant value (if any) */
-} Vardesc;
-
-
-
-/* description of pending goto statements and label statements */
-typedef struct Labeldesc {
- TString *name; /* label identifier */
- int pc; /* position in code */
- int line; /* line where it appeared */
- short nactvar; /* number of active variables in that position */
- lu_byte close; /* true for goto that escapes upvalues */
-} Labeldesc;
-
-
-/* list of labels or gotos */
-typedef struct Labellist {
- Labeldesc *arr; /* array */
- int n; /* number of entries in use */
- int size; /* array size */
-} Labellist;
-
-
-/* dynamic structures used by the parser */
-typedef struct Dyndata {
- struct { /* list of all active local variables */
- Vardesc *arr;
- int n;
- int size;
- } actvar;
- Labellist gt; /* list of pending gotos */
- Labellist label; /* list of active labels */
-} Dyndata;
-
-
-/* control of blocks */
-struct BlockCnt; /* defined in lparser.c */
-
-
-/* state needed to generate code for a given function */
-typedef struct FuncState {
- Proto *f; /* current function header */
- struct FuncState *prev; /* enclosing function */
- struct LexState *ls; /* lexical state */
- struct BlockCnt *bl; /* chain of current blocks */
- Table *kcache; /* cache for reusing constants */
- int pc; /* next position to code (equivalent to 'ncode') */
- int lasttarget; /* 'label' of last 'jump label' */
- int previousline; /* last line that was saved in 'lineinfo' */
- int nk; /* number of elements in 'k' */
- int np; /* number of elements in 'p' */
- int nabslineinfo; /* number of elements in 'abslineinfo' */
- int firstlocal; /* index of first local var (in Dyndata array) */
- int firstlabel; /* index of first label (in 'dyd->label->arr') */
- short ndebugvars; /* number of elements in 'f->locvars' */
- short nactvar; /* number of active variable declarations */
- lu_byte nups; /* number of upvalues */
- lu_byte freereg; /* first free register */
- lu_byte iwthabs; /* instructions issued since last absolute line info */
- lu_byte needclose; /* function needs to close upvalues when returning */
-} FuncState;
-
-
-LUAI_FUNC lu_byte luaY_nvarstack (FuncState *fs);
-LUAI_FUNC void luaY_checklimit (FuncState *fs, int v, int l,
- const char *what);
-LUAI_FUNC LClosure *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff,
- Dyndata *dyd, const char *name, int firstchar);
-
-
-#endif
diff --git a/lstate.c b/lstate.c
deleted file mode 100644
index 7d34199198..0000000000
--- a/lstate.c
+++ /dev/null
@@ -1,425 +0,0 @@
-/*
-** $Id: lstate.c $
-** Global State
-** See Copyright Notice in lua.h
-*/
-
-#define lstate_c
-#define LUA_CORE
-
-#include "lprefix.h"
-
-
-#include
-#include
-
-#include "lua.h"
-
-#include "lapi.h"
-#include "ldebug.h"
-#include "ldo.h"
-#include "lfunc.h"
-#include "lgc.h"
-#include "llex.h"
-#include "lmem.h"
-#include "lstate.h"
-#include "lstring.h"
-#include "ltable.h"
-#include "ltm.h"
-
-
-
-#define fromstate(L) (cast(LX *, cast(lu_byte *, (L)) - offsetof(LX, l)))
-
-
-/*
-** these macros allow user-specific actions when a thread is
-** created/deleted
-*/
-#if !defined(luai_userstateopen)
-#define luai_userstateopen(L) ((void)L)
-#endif
-
-#if !defined(luai_userstateclose)
-#define luai_userstateclose(L) ((void)L)
-#endif
-
-#if !defined(luai_userstatethread)
-#define luai_userstatethread(L,L1) ((void)L)
-#endif
-
-#if !defined(luai_userstatefree)
-#define luai_userstatefree(L,L1) ((void)L)
-#endif
-
-
-/*
-** set GCdebt to a new value keeping the real number of allocated
-** objects (GCtotalobjs - GCdebt) invariant and avoiding overflows in
-** 'GCtotalobjs'.
-*/
-void luaE_setdebt (global_State *g, l_mem debt) {
- l_mem tb = gettotalbytes(g);
- lua_assert(tb > 0);
- if (debt > MAX_LMEM - tb)
- debt = MAX_LMEM - tb; /* will make GCtotalbytes == MAX_LMEM */
- g->GCtotalbytes = tb + debt;
- g->GCdebt = debt;
-}
-
-
-CallInfo *luaE_extendCI (lua_State *L, int err) {
- CallInfo *ci;
- ci = luaM_reallocvector(L, NULL, 0, 1, CallInfo);
- if (l_unlikely(ci == NULL)) { /* allocation failed? */
- if (err)
- luaM_error(L); /* raise the error */
- return NULL; /* else only report it */
- }
- ci->next = L->ci->next;
- ci->previous = L->ci;
- L->ci->next = ci;
- if (ci->next)
- ci->next->previous = ci;
- ci->u.l.trap = 0;
- L->nci++;
- return ci;
-}
-
-
-/*
-** free all CallInfo structures not in use by a thread
-*/
-static void freeCI (lua_State *L) {
- CallInfo *ci = L->ci;
- CallInfo *next = ci->next;
- ci->next = NULL;
- while ((ci = next) != NULL) {
- next = ci->next;
- luaM_free(L, ci);
- L->nci--;
- }
-}
-
-
-/*
-** free half of the CallInfo structures not in use by a thread,
-** keeping the first one.
-*/
-void luaE_shrinkCI (lua_State *L) {
- CallInfo *ci = L->ci->next; /* first free CallInfo */
- CallInfo *next;
- if (ci == NULL)
- return; /* no extra elements */
- while ((next = ci->next) != NULL) { /* two extra elements? */
- CallInfo *next2 = next->next; /* next's next */
- ci->next = next2; /* remove next from the list */
- L->nci--;
- luaM_free(L, next); /* free next */
- if (next2 == NULL)
- break; /* no more elements */
- else {
- next2->previous = ci;
- ci = next2; /* continue */
- }
- }
-}
-
-
-/*
-** Called when 'getCcalls(L)' larger or equal to LUAI_MAXCCALLS.
-** If equal, raises an overflow error. If value is larger than
-** LUAI_MAXCCALLS (which means it is handling an overflow) but
-** not much larger, does not report an error (to allow overflow
-** handling to work).
-*/
-void luaE_checkcstack (lua_State *L) {
- if (getCcalls(L) == LUAI_MAXCCALLS)
- luaG_runerror(L, "C stack overflow");
- else if (getCcalls(L) >= (LUAI_MAXCCALLS / 10 * 11))
- luaD_errerr(L); /* error while handling stack error */
-}
-
-
-LUAI_FUNC void luaE_incCstack (lua_State *L) {
- L->nCcalls++;
- if (l_unlikely(getCcalls(L) >= LUAI_MAXCCALLS))
- luaE_checkcstack(L);
-}
-
-
-static void resetCI (lua_State *L) {
- CallInfo *ci = L->ci = &L->base_ci;
- ci->func.p = L->stack.p;
- setnilvalue(s2v(ci->func.p)); /* 'function' entry for basic 'ci' */
- ci->top.p = ci->func.p + 1 + LUA_MINSTACK; /* +1 for 'function' entry */
- ci->u.c.k = NULL;
- ci->callstatus = CIST_C;
- L->status = LUA_OK;
- L->errfunc = 0; /* stack unwind can "throw away" the error function */
-}
-
-
-static void stack_init (lua_State *L1, lua_State *L) {
- int i;
- /* initialize stack array */
- L1->stack.p = luaM_newvector(L, BASIC_STACK_SIZE + EXTRA_STACK, StackValue);
- L1->tbclist.p = L1->stack.p;
- for (i = 0; i < BASIC_STACK_SIZE + EXTRA_STACK; i++)
- setnilvalue(s2v(L1->stack.p + i)); /* erase new stack */
- L1->stack_last.p = L1->stack.p + BASIC_STACK_SIZE;
- /* initialize first ci */
- resetCI(L1);
- L1->top.p = L1->stack.p + 1; /* +1 for 'function' entry */
-}
-
-
-static void freestack (lua_State *L) {
- if (L->stack.p == NULL)
- return; /* stack not completely built yet */
- L->ci = &L->base_ci; /* free the entire 'ci' list */
- freeCI(L);
- lua_assert(L->nci == 0);
- /* free stack */
- luaM_freearray(L, L->stack.p, cast_sizet(stacksize(L) + EXTRA_STACK));
-}
-
-
-/*
-** Create registry table and its predefined values
-*/
-static void init_registry (lua_State *L, global_State *g) {
- /* create registry */
- TValue aux;
- Table *registry = luaH_new(L);
- sethvalue(L, &g->l_registry, registry);
- luaH_resize(L, registry, LUA_RIDX_LAST, 0);
- /* registry[1] = false */
- setbfvalue(&aux);
- luaH_setint(L, registry, 1, &aux);
- /* registry[LUA_RIDX_MAINTHREAD] = L */
- setthvalue(L, &aux, L);
- luaH_setint(L, registry, LUA_RIDX_MAINTHREAD, &aux);
- /* registry[LUA_RIDX_GLOBALS] = new table (table of globals) */
- sethvalue(L, &aux, luaH_new(L));
- luaH_setint(L, registry, LUA_RIDX_GLOBALS, &aux);
-}
-
-
-/*
-** open parts of the state that may cause memory-allocation errors.
-*/
-static void f_luaopen (lua_State *L, void *ud) {
- global_State *g = G(L);
- UNUSED(ud);
- stack_init(L, L); /* init stack */
- init_registry(L, g);
- luaS_init(L);
- luaT_init(L);
- luaX_init(L);
- g->gcstp = 0; /* allow gc */
- setnilvalue(&g->nilvalue); /* now state is complete */
- luai_userstateopen(L);
-}
-
-
-/*
-** preinitialize a thread with consistent values without allocating
-** any memory (to avoid errors)
-*/
-static void preinit_thread (lua_State *L, global_State *g) {
- G(L) = g;
- L->stack.p = NULL;
- L->ci = NULL;
- L->nci = 0;
- L->twups = L; /* thread has no upvalues */
- L->nCcalls = 0;
- L->errorJmp = NULL;
- L->hook = NULL;
- L->hookmask = 0;
- L->basehookcount = 0;
- L->allowhook = 1;
- resethookcount(L);
- L->openupval = NULL;
- L->status = LUA_OK;
- L->errfunc = 0;
- L->oldpc = 0;
- L->base_ci.previous = L->base_ci.next = NULL;
-}
-
-
-lu_mem luaE_threadsize (lua_State *L) {
- lu_mem sz = cast(lu_mem, sizeof(LX))
- + cast_uint(L->nci) * sizeof(CallInfo);
- if (L->stack.p != NULL)
- sz += cast_uint(stacksize(L) + EXTRA_STACK) * sizeof(StackValue);
- return sz;
-}
-
-
-static void close_state (lua_State *L) {
- global_State *g = G(L);
- if (!completestate(g)) /* closing a partially built state? */
- luaC_freeallobjects(L); /* just collect its objects */
- else { /* closing a fully built state */
- resetCI(L);
- luaD_closeprotected(L, 1, LUA_OK); /* close all upvalues */
- L->top.p = L->stack.p + 1; /* empty the stack to run finalizers */
- luaC_freeallobjects(L); /* collect all objects */
- luai_userstateclose(L);
- }
- luaM_freearray(L, G(L)->strt.hash, cast_sizet(G(L)->strt.size));
- freestack(L);
- lua_assert(gettotalbytes(g) == sizeof(global_State));
- (*g->frealloc)(g->ud, g, sizeof(global_State), 0); /* free main block */
-}
-
-
-LUA_API lua_State *lua_newthread (lua_State *L) {
- global_State *g = G(L);
- GCObject *o;
- lua_State *L1;
- lua_lock(L);
- luaC_checkGC(L);
- /* create new thread */
- o = luaC_newobjdt(L, LUA_TTHREAD, sizeof(LX), offsetof(LX, l));
- L1 = gco2th(o);
- /* anchor it on L stack */
- setthvalue2s(L, L->top.p, L1);
- api_incr_top(L);
- preinit_thread(L1, g);
- L1->hookmask = L->hookmask;
- L1->basehookcount = L->basehookcount;
- L1->hook = L->hook;
- resethookcount(L1);
- /* initialize L1 extra space */
- memcpy(lua_getextraspace(L1), lua_getextraspace(mainthread(g)),
- LUA_EXTRASPACE);
- luai_userstatethread(L, L1);
- stack_init(L1, L); /* init stack */
- lua_unlock(L);
- return L1;
-}
-
-
-void luaE_freethread (lua_State *L, lua_State *L1) {
- LX *l = fromstate(L1);
- luaF_closeupval(L1, L1->stack.p); /* close all upvalues */
- lua_assert(L1->openupval == NULL);
- luai_userstatefree(L, L1);
- freestack(L1);
- luaM_free(L, l);
-}
-
-
-TStatus luaE_resetthread (lua_State *L, TStatus status) {
- resetCI(L);
- if (status == LUA_YIELD)
- status = LUA_OK;
- status = luaD_closeprotected(L, 1, status);
- if (status != LUA_OK) /* errors? */
- luaD_seterrorobj(L, status, L->stack.p + 1);
- else
- L->top.p = L->stack.p + 1;
- luaD_reallocstack(L, cast_int(L->ci->top.p - L->stack.p), 0);
- return status;
-}
-
-
-LUA_API int lua_closethread (lua_State *L, lua_State *from) {
- TStatus status;
- lua_lock(L);
- L->nCcalls = (from) ? getCcalls(from) : 0;
- status = luaE_resetthread(L, L->status);
- if (L == from) /* closing itself? */
- luaD_throwbaselevel(L, status);
- lua_unlock(L);
- return APIstatus(status);
-}
-
-
-LUA_API lua_State *lua_newstate (lua_Alloc f, void *ud, unsigned seed) {
- int i;
- lua_State *L;
- global_State *g = cast(global_State*,
- (*f)(ud, NULL, LUA_TTHREAD, sizeof(global_State)));
- if (g == NULL) return NULL;
- L = &g->mainth.l;
- L->tt = LUA_VTHREAD;
- g->currentwhite = bitmask(WHITE0BIT);
- L->marked = luaC_white(g);
- preinit_thread(L, g);
- g->allgc = obj2gco(L); /* by now, only object is the main thread */
- L->next = NULL;
- incnny(L); /* main thread is always non yieldable */
- g->frealloc = f;
- g->ud = ud;
- g->warnf = NULL;
- g->ud_warn = NULL;
- g->seed = seed;
- g->gcstp = GCSTPGC; /* no GC while building state */
- g->strt.size = g->strt.nuse = 0;
- g->strt.hash = NULL;
- setnilvalue(&g->l_registry);
- g->panic = NULL;
- g->gcstate = GCSpause;
- g->gckind = KGC_INC;
- g->gcstopem = 0;
- g->gcemergency = 0;
- g->finobj = g->tobefnz = g->fixedgc = NULL;
- g->firstold1 = g->survival = g->old1 = g->reallyold = NULL;
- g->finobjsur = g->finobjold1 = g->finobjrold = NULL;
- g->sweepgc = NULL;
- g->gray = g->grayagain = NULL;
- g->weak = g->ephemeron = g->allweak = NULL;
- g->twups = NULL;
- g->GCtotalbytes = sizeof(global_State);
- g->GCmarked = 0;
- g->GCdebt = 0;
- setivalue(&g->nilvalue, 0); /* to signal that state is not yet built */
- setgcparam(g, PAUSE, LUAI_GCPAUSE);
- setgcparam(g, STEPMUL, LUAI_GCMUL);
- setgcparam(g, STEPSIZE, LUAI_GCSTEPSIZE);
- setgcparam(g, MINORMUL, LUAI_GENMINORMUL);
- setgcparam(g, MINORMAJOR, LUAI_MINORMAJOR);
- setgcparam(g, MAJORMINOR, LUAI_MAJORMINOR);
- for (i=0; i < LUA_NUMTYPES; i++) g->mt[i] = NULL;
- if (luaD_rawrunprotected(L, f_luaopen, NULL) != LUA_OK) {
- /* memory allocation error: free partial state */
- close_state(L);
- L = NULL;
- }
- return L;
-}
-
-
-LUA_API void lua_close (lua_State *L) {
- lua_lock(L);
- L = mainthread(G(L)); /* only the main thread can be closed */
- close_state(L);
-}
-
-
-void luaE_warning (lua_State *L, const char *msg, int tocont) {
- lua_WarnFunction wf = G(L)->warnf;
- if (wf != NULL)
- wf(G(L)->ud_warn, msg, tocont);
-}
-
-
-/*
-** Generate a warning from an error message
-*/
-void luaE_warnerror (lua_State *L, const char *where) {
- TValue *errobj = s2v(L->top.p - 1); /* error object */
- const char *msg = (ttisstring(errobj))
- ? getstr(tsvalue(errobj))
- : "error object is not a string";
- /* produce warning "error in %s (%s)" (where, msg) */
- luaE_warning(L, "error in ", 1);
- luaE_warning(L, where, 1);
- luaE_warning(L, " (", 1);
- luaE_warning(L, msg, 1);
- luaE_warning(L, ")", 0);
-}
-
diff --git a/lstate.h b/lstate.h
deleted file mode 100644
index 013872835d..0000000000
--- a/lstate.h
+++ /dev/null
@@ -1,451 +0,0 @@
-/*
-** $Id: lstate.h $
-** Global State
-** See Copyright Notice in lua.h
-*/
-
-#ifndef lstate_h
-#define lstate_h
-
-#include "lua.h"
-
-
-/* Some header files included here need this definition */
-typedef struct CallInfo CallInfo;
-
-
-#include "lobject.h"
-#include "ltm.h"
-#include "lzio.h"
-
-
-/*
-** Some notes about garbage-collected objects: All objects in Lua must
-** be kept somehow accessible until being freed, so all objects always
-** belong to one (and only one) of these lists, using field 'next' of
-** the 'CommonHeader' for the link:
-**
-** 'allgc': all objects not marked for finalization;
-** 'finobj': all objects marked for finalization;
-** 'tobefnz': all objects ready to be finalized;
-** 'fixedgc': all objects that are not to be collected (currently
-** only small strings, such as reserved words).
-**
-** For the generational collector, some of these lists have marks for
-** generations. Each mark points to the first element in the list for
-** that particular generation; that generation goes until the next mark.
-**
-** 'allgc' -> 'survival': new objects;
-** 'survival' -> 'old': objects that survived one collection;
-** 'old1' -> 'reallyold': objects that became old in last collection;
-** 'reallyold' -> NULL: objects old for more than one cycle.
-**
-** 'finobj' -> 'finobjsur': new objects marked for finalization;
-** 'finobjsur' -> 'finobjold1': survived """";
-** 'finobjold1' -> 'finobjrold': just old """";
-** 'finobjrold' -> NULL: really old """".
-**
-** All lists can contain elements older than their main ages, due
-** to 'luaC_checkfinalizer' and 'udata2finalize', which move
-** objects between the normal lists and the "marked for finalization"
-** lists. Moreover, barriers can age young objects in young lists as
-** OLD0, which then become OLD1. However, a list never contains
-** elements younger than their main ages.
-**
-** The generational collector also uses a pointer 'firstold1', which
-** points to the first OLD1 object in the list. It is used to optimize
-** 'markold'. (Potentially OLD1 objects can be anywhere between 'allgc'
-** and 'reallyold', but often the list has no OLD1 objects or they are
-** after 'old1'.) Note the difference between it and 'old1':
-** 'firstold1': no OLD1 objects before this point; there can be all
-** ages after it.
-** 'old1': no objects younger than OLD1 after this point.
-*/
-
-/*
-** Moreover, there is another set of lists that control gray objects.
-** These lists are linked by fields 'gclist'. (All objects that
-** can become gray have such a field. The field is not the same
-** in all objects, but it always has this name.) Any gray object
-** must belong to one of these lists, and all objects in these lists
-** must be gray (with two exceptions explained below):
-**
-** 'gray': regular gray objects, still waiting to be visited.
-** 'grayagain': objects that must be revisited at the atomic phase.
-** That includes
-** - black objects got in a write barrier;
-** - all kinds of weak tables during propagation phase;
-** - all threads.
-** 'weak': tables with weak values to be cleared;
-** 'ephemeron': ephemeron tables with white->white entries;
-** 'allweak': tables with weak keys and/or weak values to be cleared.
-**
-** The exceptions to that "gray rule" are:
-** - TOUCHED2 objects in generational mode stay in a gray list (because
-** they must be visited again at the end of the cycle), but they are
-** marked black because assignments to them must activate barriers (to
-** move them back to TOUCHED1).
-** - Open upvalues are kept gray to avoid barriers, but they stay out
-** of gray lists. (They don't even have a 'gclist' field.)
-*/
-
-
-
-/*
-** About 'nCcalls': This count has two parts: the lower 16 bits counts
-** the number of recursive invocations in the C stack; the higher
-** 16 bits counts the number of non-yieldable calls in the stack.
-** (They are together so that we can change and save both with one
-** instruction.)
-*/
-
-
-/* true if this thread does not have non-yieldable calls in the stack */
-#define yieldable(L) (((L)->nCcalls & 0xffff0000) == 0)
-
-/* real number of C calls */
-#define getCcalls(L) ((L)->nCcalls & 0xffff)
-
-
-/* Increment the number of non-yieldable calls */
-#define incnny(L) ((L)->nCcalls += 0x10000)
-
-/* Decrement the number of non-yieldable calls */
-#define decnny(L) ((L)->nCcalls -= 0x10000)
-
-/* Non-yieldable call increment */
-#define nyci (0x10000 | 1)
-
-
-
-
-struct lua_longjmp; /* defined in ldo.c */
-
-
-/*
-** Atomic type (relative to signals) to better ensure that 'lua_sethook'
-** is thread safe
-*/
-#if !defined(l_signalT)
-#include
-#define l_signalT sig_atomic_t
-#endif
-
-
-/*
-** Extra stack space to handle TM calls and some other extras. This
-** space is not included in 'stack_last'. It is used only to avoid stack
-** checks, either because the element will be promptly popped or because
-** there will be a stack check soon after the push. Function frames
-** never use this extra space, so it does not need to be kept clean.
-*/
-#define EXTRA_STACK 5
-
-
-/*
-** Size of cache for strings in the API. 'N' is the number of
-** sets (better be a prime) and "M" is the size of each set.
-** (M == 1 makes a direct cache.)
-*/
-#if !defined(STRCACHE_N)
-#define STRCACHE_N 53
-#define STRCACHE_M 2
-#endif
-
-
-#define BASIC_STACK_SIZE (2*LUA_MINSTACK)
-
-#define stacksize(th) cast_int((th)->stack_last.p - (th)->stack.p)
-
-
-/* kinds of Garbage Collection */
-#define KGC_INC 0 /* incremental gc */
-#define KGC_GENMINOR 1 /* generational gc in minor (regular) mode */
-#define KGC_GENMAJOR 2 /* generational in major mode */
-
-
-typedef struct stringtable {
- TString **hash; /* array of buckets (linked lists of strings) */
- int nuse; /* number of elements */
- int size; /* number of buckets */
-} stringtable;
-
-
-/*
-** Information about a call.
-** About union 'u':
-** - field 'l' is used only for Lua functions;
-** - field 'c' is used only for C functions.
-** About union 'u2':
-** - field 'funcidx' is used only by C functions while doing a
-** protected call;
-** - field 'nyield' is used only while a function is "doing" an
-** yield (from the yield until the next resume);
-** - field 'nres' is used only while closing tbc variables when
-** returning from a function;
-*/
-struct CallInfo {
- StkIdRel func; /* function index in the stack */
- StkIdRel top; /* top for this function */
- struct CallInfo *previous, *next; /* dynamic call link */
- union {
- struct { /* only for Lua functions */
- const Instruction *savedpc;
- volatile l_signalT trap; /* function is tracing lines/counts */
- int nextraargs; /* # of extra arguments in vararg functions */
- } l;
- struct { /* only for C functions */
- lua_KFunction k; /* continuation in case of yields */
- ptrdiff_t old_errfunc;
- lua_KContext ctx; /* context info. in case of yields */
- } c;
- } u;
- union {
- int funcidx; /* called-function index */
- int nyield; /* number of values yielded */
- int nres; /* number of values returned */
- } u2;
- l_uint32 callstatus;
-};
-
-
-/*
-** Maximum expected number of results from a function
-** (must fit in CIST_NRESULTS).
-*/
-#define MAXRESULTS 250
-
-
-/*
-** Bits in CallInfo status
-*/
-/* bits 0-7 are the expected number of results from this function + 1 */
-#define CIST_NRESULTS 0xffu
-
-/* bits 8-11 count call metamethods (and their extra arguments) */
-#define CIST_CCMT 8 /* the offset, not the mask */
-#define MAX_CCMT (0xfu << CIST_CCMT)
-
-/* Bits 12-14 are used for CIST_RECST (see below) */
-#define CIST_RECST 12 /* the offset, not the mask */
-
-/* call is running a C function (still in first 16 bits) */
-#define CIST_C (1u << (CIST_RECST + 3))
-/* call is on a fresh "luaV_execute" frame */
-#define CIST_FRESH (cast(l_uint32, CIST_C) << 1)
-/* function is closing tbc variables */
-#define CIST_CLSRET (CIST_FRESH << 1)
-/* function has tbc variables to close */
-#define CIST_TBC (CIST_CLSRET << 1)
-/* original value of 'allowhook' */
-#define CIST_OAH (CIST_TBC << 1)
-/* call is running a debug hook */
-#define CIST_HOOKED (CIST_OAH << 1)
-/* doing a yieldable protected call */
-#define CIST_YPCALL (CIST_HOOKED << 1)
-/* call was tail called */
-#define CIST_TAIL (CIST_YPCALL << 1)
-/* last hook called yielded */
-#define CIST_HOOKYIELD (CIST_TAIL << 1)
-/* function "called" a finalizer */
-#define CIST_FIN (CIST_HOOKYIELD << 1)
-
-
-#define get_nresults(cs) (cast_int((cs) & CIST_NRESULTS) - 1)
-
-/*
-** Field CIST_RECST stores the "recover status", used to keep the error
-** status while closing to-be-closed variables in coroutines, so that
-** Lua can correctly resume after an yield from a __close method called
-** because of an error. (Three bits are enough for error status.)
-*/
-#define getcistrecst(ci) (((ci)->callstatus >> CIST_RECST) & 7)
-#define setcistrecst(ci,st) \
- check_exp(((st) & 7) == (st), /* status must fit in three bits */ \
- ((ci)->callstatus = ((ci)->callstatus & ~(7u << CIST_RECST)) \
- | (cast(l_uint32, st) << CIST_RECST)))
-
-
-/* active function is a Lua function */
-#define isLua(ci) (!((ci)->callstatus & CIST_C))
-
-/* call is running Lua code (not a hook) */
-#define isLuacode(ci) (!((ci)->callstatus & (CIST_C | CIST_HOOKED)))
-
-
-#define setoah(ci,v) \
- ((ci)->callstatus = ((v) ? (ci)->callstatus | CIST_OAH \
- : (ci)->callstatus & ~CIST_OAH))
-#define getoah(ci) (((ci)->callstatus & CIST_OAH) ? 1 : 0)
-
-
-/*
-** 'per thread' state
-*/
-struct lua_State {
- CommonHeader;
- lu_byte allowhook;
- TStatus status;
- StkIdRel top; /* first free slot in the stack */
- struct global_State *l_G;
- CallInfo *ci; /* call info for current function */
- StkIdRel stack_last; /* end of stack (last element + 1) */
- StkIdRel stack; /* stack base */
- UpVal *openupval; /* list of open upvalues in this stack */
- StkIdRel tbclist; /* list of to-be-closed variables */
- GCObject *gclist;
- struct lua_State *twups; /* list of threads with open upvalues */
- struct lua_longjmp *errorJmp; /* current error recover point */
- CallInfo base_ci; /* CallInfo for first level (C host) */
- volatile lua_Hook hook;
- ptrdiff_t errfunc; /* current error handling function (stack index) */
- l_uint32 nCcalls; /* number of nested non-yieldable or C calls */
- int oldpc; /* last pc traced */
- int nci; /* number of items in 'ci' list */
- int basehookcount;
- int hookcount;
- volatile l_signalT hookmask;
- struct { /* info about transferred values (for call/return hooks) */
- int ftransfer; /* offset of first value transferred */
- int ntransfer; /* number of values transferred */
- } transferinfo;
-};
-
-
-/*
-** thread state + extra space
-*/
-typedef struct LX {
- lu_byte extra_[LUA_EXTRASPACE];
- lua_State l;
-} LX;
-
-
-/*
-** 'global state', shared by all threads of this state
-*/
-typedef struct global_State {
- lua_Alloc frealloc; /* function to reallocate memory */
- void *ud; /* auxiliary data to 'frealloc' */
- l_mem GCtotalbytes; /* number of bytes currently allocated + debt */
- l_mem GCdebt; /* bytes counted but not yet allocated */
- l_mem GCmarked; /* number of objects marked in a GC cycle */
- l_mem GCmajorminor; /* auxiliary counter to control major-minor shifts */
- stringtable strt; /* hash table for strings */
- TValue l_registry;
- TValue nilvalue; /* a nil value */
- unsigned int seed; /* randomized seed for hashes */
- lu_byte gcparams[LUA_GCPN];
- lu_byte currentwhite;
- lu_byte gcstate; /* state of garbage collector */
- lu_byte gckind; /* kind of GC running */
- lu_byte gcstopem; /* stops emergency collections */
- lu_byte gcstp; /* control whether GC is running */
- lu_byte gcemergency; /* true if this is an emergency collection */
- GCObject *allgc; /* list of all collectable objects */
- GCObject **sweepgc; /* current position of sweep in list */
- GCObject *finobj; /* list of collectable objects with finalizers */
- GCObject *gray; /* list of gray objects */
- GCObject *grayagain; /* list of objects to be traversed atomically */
- GCObject *weak; /* list of tables with weak values */
- GCObject *ephemeron; /* list of ephemeron tables (weak keys) */
- GCObject *allweak; /* list of all-weak tables */
- GCObject *tobefnz; /* list of userdata to be GC */
- GCObject *fixedgc; /* list of objects not to be collected */
- /* fields for generational collector */
- GCObject *survival; /* start of objects that survived one GC cycle */
- GCObject *old1; /* start of old1 objects */
- GCObject *reallyold; /* objects more than one cycle old ("really old") */
- GCObject *firstold1; /* first OLD1 object in the list (if any) */
- GCObject *finobjsur; /* list of survival objects with finalizers */
- GCObject *finobjold1; /* list of old1 objects with finalizers */
- GCObject *finobjrold; /* list of really old objects with finalizers */
- struct lua_State *twups; /* list of threads with open upvalues */
- lua_CFunction panic; /* to be called in unprotected errors */
- TString *memerrmsg; /* message for memory-allocation errors */
- TString *tmname[TM_N]; /* array with tag-method names */
- struct Table *mt[LUA_NUMTYPES]; /* metatables for basic types */
- TString *strcache[STRCACHE_N][STRCACHE_M]; /* cache for strings in API */
- lua_WarnFunction warnf; /* warning function */
- void *ud_warn; /* auxiliary data to 'warnf' */
- LX mainth; /* main thread of this state */
-} global_State;
-
-
-#define G(L) (L->l_G)
-#define mainthread(G) (&(G)->mainth.l)
-
-/*
-** 'g->nilvalue' being a nil value flags that the state was completely
-** build.
-*/
-#define completestate(g) ttisnil(&g->nilvalue)
-
-
-/*
-** Union of all collectable objects (only for conversions)
-** ISO C99, 6.5.2.3 p.5:
-** "if a union contains several structures that share a common initial
-** sequence [...], and if the union object currently contains one
-** of these structures, it is permitted to inspect the common initial
-** part of any of them anywhere that a declaration of the complete type
-** of the union is visible."
-*/
-union GCUnion {
- GCObject gc; /* common header */
- struct TString ts;
- struct Udata u;
- union Closure cl;
- struct Table h;
- struct Proto p;
- struct lua_State th; /* thread */
- struct UpVal upv;
-};
-
-
-/*
-** ISO C99, 6.7.2.1 p.14:
-** "A pointer to a union object, suitably converted, points to each of
-** its members [...], and vice versa."
-*/
-#define cast_u(o) cast(union GCUnion *, (o))
-
-/* macros to convert a GCObject into a specific value */
-#define gco2ts(o) \
- check_exp(novariant((o)->tt) == LUA_TSTRING, &((cast_u(o))->ts))
-#define gco2u(o) check_exp((o)->tt == LUA_VUSERDATA, &((cast_u(o))->u))
-#define gco2lcl(o) check_exp((o)->tt == LUA_VLCL, &((cast_u(o))->cl.l))
-#define gco2ccl(o) check_exp((o)->tt == LUA_VCCL, &((cast_u(o))->cl.c))
-#define gco2cl(o) \
- check_exp(novariant((o)->tt) == LUA_TFUNCTION, &((cast_u(o))->cl))
-#define gco2t(o) check_exp((o)->tt == LUA_VTABLE, &((cast_u(o))->h))
-#define gco2p(o) check_exp((o)->tt == LUA_VPROTO, &((cast_u(o))->p))
-#define gco2th(o) check_exp((o)->tt == LUA_VTHREAD, &((cast_u(o))->th))
-#define gco2upv(o) check_exp((o)->tt == LUA_VUPVAL, &((cast_u(o))->upv))
-
-
-/*
-** macro to convert a Lua object into a GCObject
-*/
-#define obj2gco(v) \
- check_exp(novariant((v)->tt) >= LUA_TSTRING, &(cast_u(v)->gc))
-
-
-/* actual number of total memory allocated */
-#define gettotalbytes(g) ((g)->GCtotalbytes - (g)->GCdebt)
-
-
-LUAI_FUNC void luaE_setdebt (global_State *g, l_mem debt);
-LUAI_FUNC void luaE_freethread (lua_State *L, lua_State *L1);
-LUAI_FUNC lu_mem luaE_threadsize (lua_State *L);
-LUAI_FUNC CallInfo *luaE_extendCI (lua_State *L, int err);
-LUAI_FUNC void luaE_shrinkCI (lua_State *L);
-LUAI_FUNC void luaE_checkcstack (lua_State *L);
-LUAI_FUNC void luaE_incCstack (lua_State *L);
-LUAI_FUNC void luaE_warning (lua_State *L, const char *msg, int tocont);
-LUAI_FUNC void luaE_warnerror (lua_State *L, const char *where);
-LUAI_FUNC TStatus luaE_resetthread (lua_State *L, TStatus status);
-
-
-#endif
-
diff --git a/lstring.c b/lstring.c
deleted file mode 100644
index 75635142e9..0000000000
--- a/lstring.c
+++ /dev/null
@@ -1,353 +0,0 @@
-/*
-** $Id: lstring.c $
-** String table (keeps all strings handled by Lua)
-** See Copyright Notice in lua.h
-*/
-
-#define lstring_c
-#define LUA_CORE
-
-#include "lprefix.h"
-
-
-#include
-
-#include "lua.h"
-
-#include "ldebug.h"
-#include "ldo.h"
-#include "lmem.h"
-#include "lobject.h"
-#include "lstate.h"
-#include "lstring.h"
-
-
-/*
-** Maximum size for string table.
-*/
-#define MAXSTRTB cast_int(luaM_limitN(INT_MAX, TString*))
-
-/*
-** Initial size for the string table (must be power of 2).
-** The Lua core alone registers ~50 strings (reserved words +
-** metaevent keys + a few others). Libraries would typically add
-** a few dozens more.
-*/
-#if !defined(MINSTRTABSIZE)
-#define MINSTRTABSIZE 128
-#endif
-
-
-/*
-** generic equality for strings
-*/
-int luaS_eqstr (TString *a, TString *b) {
- size_t len1, len2;
- const char *s1 = getlstr(a, len1);
- const char *s2 = getlstr(b, len2);
- return ((len1 == len2) && /* equal length and ... */
- (memcmp(s1, s2, len1) == 0)); /* equal contents */
-}
-
-
-static unsigned luaS_hash (const char *str, size_t l, unsigned seed) {
- unsigned int h = seed ^ cast_uint(l);
- for (; l > 0; l--)
- h ^= ((h<<5) + (h>>2) + cast_byte(str[l - 1]));
- return h;
-}
-
-
-unsigned luaS_hashlongstr (TString *ts) {
- lua_assert(ts->tt == LUA_VLNGSTR);
- if (ts->extra == 0) { /* no hash? */
- size_t len = ts->u.lnglen;
- ts->hash = luaS_hash(getlngstr(ts), len, ts->hash);
- ts->extra = 1; /* now it has its hash */
- }
- return ts->hash;
-}
-
-
-static void tablerehash (TString **vect, int osize, int nsize) {
- int i;
- for (i = osize; i < nsize; i++) /* clear new elements */
- vect[i] = NULL;
- for (i = 0; i < osize; i++) { /* rehash old part of the array */
- TString *p = vect[i];
- vect[i] = NULL;
- while (p) { /* for each string in the list */
- TString *hnext = p->u.hnext; /* save next */
- unsigned int h = lmod(p->hash, nsize); /* new position */
- p->u.hnext = vect[h]; /* chain it into array */
- vect[h] = p;
- p = hnext;
- }
- }
-}
-
-
-/*
-** Resize the string table. If allocation fails, keep the current size.
-** (This can degrade performance, but any non-zero size should work
-** correctly.)
-*/
-void luaS_resize (lua_State *L, int nsize) {
- stringtable *tb = &G(L)->strt;
- int osize = tb->size;
- TString **newvect;
- if (nsize < osize) /* shrinking table? */
- tablerehash(tb->hash, osize, nsize); /* depopulate shrinking part */
- newvect = luaM_reallocvector(L, tb->hash, osize, nsize, TString*);
- if (l_unlikely(newvect == NULL)) { /* reallocation failed? */
- if (nsize < osize) /* was it shrinking table? */
- tablerehash(tb->hash, nsize, osize); /* restore to original size */
- /* leave table as it was */
- }
- else { /* allocation succeeded */
- tb->hash = newvect;
- tb->size = nsize;
- if (nsize > osize)
- tablerehash(newvect, osize, nsize); /* rehash for new size */
- }
-}
-
-
-/*
-** Clear API string cache. (Entries cannot be empty, so fill them with
-** a non-collectable string.)
-*/
-void luaS_clearcache (global_State *g) {
- int i, j;
- for (i = 0; i < STRCACHE_N; i++)
- for (j = 0; j < STRCACHE_M; j++) {
- if (iswhite(g->strcache[i][j])) /* will entry be collected? */
- g->strcache[i][j] = g->memerrmsg; /* replace it with something fixed */
- }
-}
-
-
-/*
-** Initialize the string table and the string cache
-*/
-void luaS_init (lua_State *L) {
- global_State *g = G(L);
- int i, j;
- stringtable *tb = &G(L)->strt;
- tb->hash = luaM_newvector(L, MINSTRTABSIZE, TString*);
- tablerehash(tb->hash, 0, MINSTRTABSIZE); /* clear array */
- tb->size = MINSTRTABSIZE;
- /* pre-create memory-error message */
- g->memerrmsg = luaS_newliteral(L, MEMERRMSG);
- luaC_fix(L, obj2gco(g->memerrmsg)); /* it should never be collected */
- for (i = 0; i < STRCACHE_N; i++) /* fill cache with valid strings */
- for (j = 0; j < STRCACHE_M; j++)
- g->strcache[i][j] = g->memerrmsg;
-}
-
-
-size_t luaS_sizelngstr (size_t len, int kind) {
- switch (kind) {
- case LSTRREG: /* regular long string */
- /* don't need 'falloc'/'ud', but need space for content */
- return offsetof(TString, falloc) + (len + 1) * sizeof(char);
- case LSTRFIX: /* fixed external long string */
- /* don't need 'falloc'/'ud' */
- return offsetof(TString, falloc);
- default: /* external long string with deallocation */
- lua_assert(kind == LSTRMEM);
- return sizeof(TString);
- }
-}
-
-
-/*
-** creates a new string object
-*/
-static TString *createstrobj (lua_State *L, size_t totalsize, lu_byte tag,
- unsigned h) {
- TString *ts;
- GCObject *o;
- o = luaC_newobj(L, tag, totalsize);
- ts = gco2ts(o);
- ts->hash = h;
- ts->extra = 0;
- return ts;
-}
-
-
-TString *luaS_createlngstrobj (lua_State *L, size_t l) {
- size_t totalsize = luaS_sizelngstr(l, LSTRREG);
- TString *ts = createstrobj(L, totalsize, LUA_VLNGSTR, G(L)->seed);
- ts->u.lnglen = l;
- ts->shrlen = LSTRREG; /* signals that it is a regular long string */
- ts->contents = cast_charp(ts) + offsetof(TString, falloc);
- ts->contents[l] = '\0'; /* ending 0 */
- return ts;
-}
-
-
-void luaS_remove (lua_State *L, TString *ts) {
- stringtable *tb = &G(L)->strt;
- TString **p = &tb->hash[lmod(ts->hash, tb->size)];
- while (*p != ts) /* find previous element */
- p = &(*p)->u.hnext;
- *p = (*p)->u.hnext; /* remove element from its list */
- tb->nuse--;
-}
-
-
-static void growstrtab (lua_State *L, stringtable *tb) {
- if (l_unlikely(tb->nuse == INT_MAX)) { /* too many strings? */
- luaC_fullgc(L, 1); /* try to free some... */
- if (tb->nuse == INT_MAX) /* still too many? */
- luaM_error(L); /* cannot even create a message... */
- }
- if (tb->size <= MAXSTRTB / 2) /* can grow string table? */
- luaS_resize(L, tb->size * 2);
-}
-
-
-/*
-** Checks whether short string exists and reuses it or creates a new one.
-*/
-static TString *internshrstr (lua_State *L, const char *str, size_t l) {
- TString *ts;
- global_State *g = G(L);
- stringtable *tb = &g->strt;
- unsigned int h = luaS_hash(str, l, g->seed);
- TString **list = &tb->hash[lmod(h, tb->size)];
- lua_assert(str != NULL); /* otherwise 'memcmp'/'memcpy' are undefined */
- for (ts = *list; ts != NULL; ts = ts->u.hnext) {
- if (l == cast_uint(ts->shrlen) &&
- (memcmp(str, getshrstr(ts), l * sizeof(char)) == 0)) {
- /* found! */
- if (isdead(g, ts)) /* dead (but not collected yet)? */
- changewhite(ts); /* resurrect it */
- return ts;
- }
- }
- /* else must create a new string */
- if (tb->nuse >= tb->size) { /* need to grow string table? */
- growstrtab(L, tb);
- list = &tb->hash[lmod(h, tb->size)]; /* rehash with new size */
- }
- ts = createstrobj(L, sizestrshr(l), LUA_VSHRSTR, h);
- ts->shrlen = cast(ls_byte, l);
- getshrstr(ts)[l] = '\0'; /* ending 0 */
- memcpy(getshrstr(ts), str, l * sizeof(char));
- ts->u.hnext = *list;
- *list = ts;
- tb->nuse++;
- return ts;
-}
-
-
-/*
-** new string (with explicit length)
-*/
-TString *luaS_newlstr (lua_State *L, const char *str, size_t l) {
- if (l <= LUAI_MAXSHORTLEN) /* short string? */
- return internshrstr(L, str, l);
- else {
- TString *ts;
- if (l_unlikely(l * sizeof(char) >= (MAX_SIZE - sizeof(TString))))
- luaM_toobig(L);
- ts = luaS_createlngstrobj(L, l);
- memcpy(getlngstr(ts), str, l * sizeof(char));
- return ts;
- }
-}
-
-
-/*
-** Create or reuse a zero-terminated string, first checking in the
-** cache (using the string address as a key). The cache can contain
-** only zero-terminated strings, so it is safe to use 'strcmp' to
-** check hits.
-*/
-TString *luaS_new (lua_State *L, const char *str) {
- unsigned int i = point2uint(str) % STRCACHE_N; /* hash */
- int j;
- TString **p = G(L)->strcache[i];
- for (j = 0; j < STRCACHE_M; j++) {
- if (strcmp(str, getstr(p[j])) == 0) /* hit? */
- return p[j]; /* that is it */
- }
- /* normal route */
- for (j = STRCACHE_M - 1; j > 0; j--)
- p[j] = p[j - 1]; /* move out last element */
- /* new element is first in the list */
- p[0] = luaS_newlstr(L, str, strlen(str));
- return p[0];
-}
-
-
-Udata *luaS_newudata (lua_State *L, size_t s, unsigned short nuvalue) {
- Udata *u;
- int i;
- GCObject *o;
- if (l_unlikely(s > MAX_SIZE - udatamemoffset(nuvalue)))
- luaM_toobig(L);
- o = luaC_newobj(L, LUA_VUSERDATA, sizeudata(nuvalue, s));
- u = gco2u(o);
- u->len = s;
- u->nuvalue = nuvalue;
- u->metatable = NULL;
- for (i = 0; i < nuvalue; i++)
- setnilvalue(&u->uv[i].uv);
- return u;
-}
-
-
-struct NewExt {
- ls_byte kind;
- const char *s;
- size_t len;
- TString *ts; /* output */
-};
-
-
-static void f_newext (lua_State *L, void *ud) {
- struct NewExt *ne = cast(struct NewExt *, ud);
- size_t size = luaS_sizelngstr(0, ne->kind);
- ne->ts = createstrobj(L, size, LUA_VLNGSTR, G(L)->seed);
-}
-
-
-TString *luaS_newextlstr (lua_State *L,
- const char *s, size_t len, lua_Alloc falloc, void *ud) {
- struct NewExt ne;
- if (!falloc) {
- ne.kind = LSTRFIX;
- f_newext(L, &ne); /* just create header */
- }
- else {
- ne.kind = LSTRMEM;
- if (luaD_rawrunprotected(L, f_newext, &ne) != LUA_OK) { /* mem. error? */
- (*falloc)(ud, cast_voidp(s), len + 1, 0); /* free external string */
- luaM_error(L); /* re-raise memory error */
- }
- ne.ts->falloc = falloc;
- ne.ts->ud = ud;
- }
- ne.ts->shrlen = ne.kind;
- ne.ts->u.lnglen = len;
- ne.ts->contents = cast_charp(s);
- return ne.ts;
-}
-
-
-/*
-** Normalize an external string: If it is short, internalize it.
-*/
-TString *luaS_normstr (lua_State *L, TString *ts) {
- size_t len = ts->u.lnglen;
- if (len > LUAI_MAXSHORTLEN)
- return ts; /* long string; keep the original */
- else {
- const char *str = getlngstr(ts);
- return internshrstr(L, str, len);
- }
-}
-
diff --git a/lstring.h b/lstring.h
deleted file mode 100644
index 1643c3d82b..0000000000
--- a/lstring.h
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
-** $Id: lstring.h $
-** String table (keep all strings handled by Lua)
-** See Copyright Notice in lua.h
-*/
-
-#ifndef lstring_h
-#define lstring_h
-
-#include "lgc.h"
-#include "lobject.h"
-#include "lstate.h"
-
-
-/*
-** Memory-allocation error message must be preallocated (it cannot
-** be created after memory is exhausted)
-*/
-#define MEMERRMSG "not enough memory"
-
-
-/*
-** Maximum length for short strings, that is, strings that are
-** internalized. (Cannot be smaller than reserved words or tags for
-** metamethods, as these strings must be internalized;
-** #("function") = 8, #("__newindex") = 10.)
-*/
-#if !defined(LUAI_MAXSHORTLEN)
-#define LUAI_MAXSHORTLEN 40
-#endif
-
-
-/*
-** Size of a short TString: Size of the header plus space for the string
-** itself (including final '\0').
-*/
-#define sizestrshr(l) \
- (offsetof(TString, contents) + ((l) + 1) * sizeof(char))
-
-
-#define luaS_newliteral(L, s) (luaS_newlstr(L, "" s, \
- (sizeof(s)/sizeof(char))-1))
-
-
-/*
-** test whether a string is a reserved word
-*/
-#define isreserved(s) (strisshr(s) && (s)->extra > 0)
-
-
-/*
-** equality for short strings, which are always internalized
-*/
-#define eqshrstr(a,b) check_exp((a)->tt == LUA_VSHRSTR, (a) == (b))
-
-
-LUAI_FUNC unsigned luaS_hashlongstr (TString *ts);
-LUAI_FUNC int luaS_eqstr (TString *a, TString *b);
-LUAI_FUNC void luaS_resize (lua_State *L, int newsize);
-LUAI_FUNC void luaS_clearcache (global_State *g);
-LUAI_FUNC void luaS_init (lua_State *L);
-LUAI_FUNC void luaS_remove (lua_State *L, TString *ts);
-LUAI_FUNC Udata *luaS_newudata (lua_State *L, size_t s,
- unsigned short nuvalue);
-LUAI_FUNC TString *luaS_newlstr (lua_State *L, const char *str, size_t l);
-LUAI_FUNC TString *luaS_new (lua_State *L, const char *str);
-LUAI_FUNC TString *luaS_createlngstrobj (lua_State *L, size_t l);
-LUAI_FUNC TString *luaS_newextlstr (lua_State *L,
- const char *s, size_t len, lua_Alloc falloc, void *ud);
-LUAI_FUNC size_t luaS_sizelngstr (size_t len, int kind);
-LUAI_FUNC TString *luaS_normstr (lua_State *L, TString *ts);
-
-#endif
diff --git a/lstrlib.c b/lstrlib.c
deleted file mode 100644
index 874cec8086..0000000000
--- a/lstrlib.c
+++ /dev/null
@@ -1,1894 +0,0 @@
-/*
-** $Id: lstrlib.c $
-** Standard library for string operations and pattern-matching
-** See Copyright Notice in lua.h
-*/
-
-#define lstrlib_c
-#define LUA_LIB
-
-#include "lprefix.h"
-
-
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-
-#include "lua.h"
-
-#include "lauxlib.h"
-#include "lualib.h"
-#include "llimits.h"
-
-
-/*
-** maximum number of captures that a pattern can do during
-** pattern-matching. This limit is arbitrary, but must fit in
-** an unsigned char.
-*/
-#if !defined(LUA_MAXCAPTURES)
-#define LUA_MAXCAPTURES 32
-#endif
-
-
-static int str_len (lua_State *L) {
- size_t l;
- luaL_checklstring(L, 1, &l);
- lua_pushinteger(L, (lua_Integer)l);
- return 1;
-}
-
-
-/*
-** translate a relative initial string position
-** (negative means back from end): clip result to [1, inf).
-** The length of any string in Lua must fit in a lua_Integer,
-** so there are no overflows in the casts.
-** The inverted comparison avoids a possible overflow
-** computing '-pos'.
-*/
-static size_t posrelatI (lua_Integer pos, size_t len) {
- if (pos > 0)
- return (size_t)pos;
- else if (pos == 0)
- return 1;
- else if (pos < -(lua_Integer)len) /* inverted comparison */
- return 1; /* clip to 1 */
- else return len + (size_t)pos + 1;
-}
-
-
-/*
-** Gets an optional ending string position from argument 'arg',
-** with default value 'def'.
-** Negative means back from end: clip result to [0, len]
-*/
-static size_t getendpos (lua_State *L, int arg, lua_Integer def,
- size_t len) {
- lua_Integer pos = luaL_optinteger(L, arg, def);
- if (pos > (lua_Integer)len)
- return len;
- else if (pos >= 0)
- return (size_t)pos;
- else if (pos < -(lua_Integer)len)
- return 0;
- else return len + (size_t)pos + 1;
-}
-
-
-static int str_sub (lua_State *L) {
- size_t l;
- const char *s = luaL_checklstring(L, 1, &l);
- size_t start = posrelatI(luaL_checkinteger(L, 2), l);
- size_t end = getendpos(L, 3, -1, l);
- if (start <= end)
- lua_pushlstring(L, s + start - 1, (end - start) + 1);
- else lua_pushliteral(L, "");
- return 1;
-}
-
-
-static int str_reverse (lua_State *L) {
- size_t l, i;
- luaL_Buffer b;
- const char *s = luaL_checklstring(L, 1, &l);
- char *p = luaL_buffinitsize(L, &b, l);
- for (i = 0; i < l; i++)
- p[i] = s[l - i - 1];
- luaL_pushresultsize(&b, l);
- return 1;
-}
-
-
-static int str_lower (lua_State *L) {
- size_t l;
- size_t i;
- luaL_Buffer b;
- const char *s = luaL_checklstring(L, 1, &l);
- char *p = luaL_buffinitsize(L, &b, l);
- for (i=0; i MAX_SIZE - lsep ||
- cast_st2S(len + lsep) > cast_st2S(MAX_SIZE) / n))
- return luaL_error(L, "resulting string too large");
- else {
- size_t totallen = (cast_sizet(n) * (len + lsep)) - lsep;
- luaL_Buffer b;
- char *p = luaL_buffinitsize(L, &b, totallen);
- while (n-- > 1) { /* first n-1 copies (followed by separator) */
- memcpy(p, s, len * sizeof(char)); p += len;
- if (lsep > 0) { /* empty 'memcpy' is not that cheap */
- memcpy(p, sep, lsep * sizeof(char)); p += lsep;
- }
- }
- memcpy(p, s, len * sizeof(char)); /* last copy without separator */
- luaL_pushresultsize(&b, totallen);
- }
- return 1;
-}
-
-
-static int str_byte (lua_State *L) {
- size_t l;
- const char *s = luaL_checklstring(L, 1, &l);
- lua_Integer pi = luaL_optinteger(L, 2, 1);
- size_t posi = posrelatI(pi, l);
- size_t pose = getendpos(L, 3, pi, l);
- int n, i;
- if (posi > pose) return 0; /* empty interval; return no values */
- if (l_unlikely(pose - posi >= (size_t)INT_MAX)) /* arithmetic overflow? */
- return luaL_error(L, "string slice too long");
- n = (int)(pose - posi) + 1;
- luaL_checkstack(L, n, "string slice too long");
- for (i=0; iinit) {
- state->init = 1;
- luaL_buffinit(L, &state->B);
- }
- if (b == NULL) { /* finishing dump? */
- luaL_pushresult(&state->B); /* push result */
- lua_replace(L, 1); /* move it to reserved slot */
- }
- else
- luaL_addlstring(&state->B, (const char *)b, size);
- return 0;
-}
-
-
-static int str_dump (lua_State *L) {
- struct str_Writer state;
- int strip = lua_toboolean(L, 2);
- luaL_argcheck(L, lua_type(L, 1) == LUA_TFUNCTION && !lua_iscfunction(L, 1),
- 1, "Lua function expected");
- /* ensure function is on the top of the stack and vacate slot 1 */
- lua_pushvalue(L, 1);
- state.init = 0;
- lua_dump(L, writer, &state, strip);
- lua_settop(L, 1); /* leave final result on top */
- return 1;
-}
-
-
-
-/*
-** {======================================================
-** METAMETHODS
-** =======================================================
-*/
-
-#if defined(LUA_NOCVTS2N) /* { */
-
-/* no coercion from strings to numbers */
-
-static const luaL_Reg stringmetamethods[] = {
- {"__index", NULL}, /* placeholder */
- {NULL, NULL}
-};
-
-#else /* }{ */
-
-static int tonum (lua_State *L, int arg) {
- if (lua_type(L, arg) == LUA_TNUMBER) { /* already a number? */
- lua_pushvalue(L, arg);
- return 1;
- }
- else { /* check whether it is a numerical string */
- size_t len;
- const char *s = lua_tolstring(L, arg, &len);
- return (s != NULL && lua_stringtonumber(L, s) == len + 1);
- }
-}
-
-
-/*
-** To be here, either the first operand was a string or the first
-** operand didn't have a corresponding metamethod. (Otherwise, that
-** other metamethod would have been called.) So, if this metamethod
-** doesn't work, the only other option would be for the second
-** operand to have a different metamethod.
-*/
-static void trymt (lua_State *L, const char *mtkey, const char *opname) {
- lua_settop(L, 2); /* back to the original arguments */
- if (l_unlikely(lua_type(L, 2) == LUA_TSTRING ||
- !luaL_getmetafield(L, 2, mtkey)))
- luaL_error(L, "attempt to %s a '%s' with a '%s'", opname,
- luaL_typename(L, -2), luaL_typename(L, -1));
- lua_insert(L, -3); /* put metamethod before arguments */
- lua_call(L, 2, 1); /* call metamethod */
-}
-
-
-static int arith (lua_State *L, int op, const char *mtname) {
- if (tonum(L, 1) && tonum(L, 2))
- lua_arith(L, op); /* result will be on the top */
- else
- trymt(L, mtname, mtname + 2);
- return 1;
-}
-
-
-static int arith_add (lua_State *L) {
- return arith(L, LUA_OPADD, "__add");
-}
-
-static int arith_sub (lua_State *L) {
- return arith(L, LUA_OPSUB, "__sub");
-}
-
-static int arith_mul (lua_State *L) {
- return arith(L, LUA_OPMUL, "__mul");
-}
-
-static int arith_mod (lua_State *L) {
- return arith(L, LUA_OPMOD, "__mod");
-}
-
-static int arith_pow (lua_State *L) {
- return arith(L, LUA_OPPOW, "__pow");
-}
-
-static int arith_div (lua_State *L) {
- return arith(L, LUA_OPDIV, "__div");
-}
-
-static int arith_idiv (lua_State *L) {
- return arith(L, LUA_OPIDIV, "__idiv");
-}
-
-static int arith_unm (lua_State *L) {
- return arith(L, LUA_OPUNM, "__unm");
-}
-
-
-static const luaL_Reg stringmetamethods[] = {
- {"__add", arith_add},
- {"__sub", arith_sub},
- {"__mul", arith_mul},
- {"__mod", arith_mod},
- {"__pow", arith_pow},
- {"__div", arith_div},
- {"__idiv", arith_idiv},
- {"__unm", arith_unm},
- {"__index", NULL}, /* placeholder */
- {NULL, NULL}
-};
-
-#endif /* } */
-
-/* }====================================================== */
-
-/*
-** {======================================================
-** PATTERN MATCHING
-** =======================================================
-*/
-
-
-#define CAP_UNFINISHED (-1)
-#define CAP_POSITION (-2)
-
-
-typedef struct MatchState {
- const char *src_init; /* init of source string */
- const char *src_end; /* end ('\0') of source string */
- const char *p_end; /* end ('\0') of pattern */
- lua_State *L;
- int matchdepth; /* control for recursive depth (to avoid C stack overflow) */
- int level; /* total number of captures (finished or unfinished) */
- struct {
- const char *init;
- ptrdiff_t len; /* length or special value (CAP_*) */
- } capture[LUA_MAXCAPTURES];
-} MatchState;
-
-
-/* recursive function */
-static const char *match (MatchState *ms, const char *s, const char *p);
-
-
-/* maximum recursion depth for 'match' */
-#if !defined(MAXCCALLS)
-#define MAXCCALLS 200
-#endif
-
-
-#define L_ESC '%'
-#define SPECIALS "^$*+?.([%-"
-
-
-static int check_capture (MatchState *ms, int l) {
- l -= '1';
- if (l_unlikely(l < 0 || l >= ms->level ||
- ms->capture[l].len == CAP_UNFINISHED))
- return luaL_error(ms->L, "invalid capture index %%%d", l + 1);
- return l;
-}
-
-
-static int capture_to_close (MatchState *ms) {
- int level = ms->level;
- for (level--; level>=0; level--)
- if (ms->capture[level].len == CAP_UNFINISHED) return level;
- return luaL_error(ms->L, "invalid pattern capture");
-}
-
-
-static const char *classend (MatchState *ms, const char *p) {
- switch (*p++) {
- case L_ESC: {
- if (l_unlikely(p == ms->p_end))
- luaL_error(ms->L, "malformed pattern (ends with '%%')");
- return p+1;
- }
- case '[': {
- if (*p == '^') p++;
- do { /* look for a ']' */
- if (l_unlikely(p == ms->p_end))
- luaL_error(ms->L, "malformed pattern (missing ']')");
- if (*(p++) == L_ESC && p < ms->p_end)
- p++; /* skip escapes (e.g. '%]') */
- } while (*p != ']');
- return p+1;
- }
- default: {
- return p;
- }
- }
-}
-
-
-static int match_class (int c, int cl) {
- int res;
- switch (tolower(cl)) {
- case 'a' : res = isalpha(c); break;
- case 'c' : res = iscntrl(c); break;
- case 'd' : res = isdigit(c); break;
- case 'g' : res = isgraph(c); break;
- case 'l' : res = islower(c); break;
- case 'p' : res = ispunct(c); break;
- case 's' : res = isspace(c); break;
- case 'u' : res = isupper(c); break;
- case 'w' : res = isalnum(c); break;
- case 'x' : res = isxdigit(c); break;
- case 'z' : res = (c == 0); break; /* deprecated option */
- default: return (cl == c);
- }
- return (islower(cl) ? res : !res);
-}
-
-
-static int matchbracketclass (int c, const char *p, const char *ec) {
- int sig = 1;
- if (*(p+1) == '^') {
- sig = 0;
- p++; /* skip the '^' */
- }
- while (++p < ec) {
- if (*p == L_ESC) {
- p++;
- if (match_class(c, cast_uchar(*p)))
- return sig;
- }
- else if ((*(p+1) == '-') && (p+2 < ec)) {
- p+=2;
- if (cast_uchar(*(p-2)) <= c && c <= cast_uchar(*p))
- return sig;
- }
- else if (cast_uchar(*p) == c) return sig;
- }
- return !sig;
-}
-
-
-static int singlematch (MatchState *ms, const char *s, const char *p,
- const char *ep) {
- if (s >= ms->src_end)
- return 0;
- else {
- int c = cast_uchar(*s);
- switch (*p) {
- case '.': return 1; /* matches any char */
- case L_ESC: return match_class(c, cast_uchar(*(p+1)));
- case '[': return matchbracketclass(c, p, ep-1);
- default: return (cast_uchar(*p) == c);
- }
- }
-}
-
-
-static const char *matchbalance (MatchState *ms, const char *s,
- const char *p) {
- if (l_unlikely(p >= ms->p_end - 1))
- luaL_error(ms->L, "malformed pattern (missing arguments to '%%b')");
- if (*s != *p) return NULL;
- else {
- int b = *p;
- int e = *(p+1);
- int cont = 1;
- while (++s < ms->src_end) {
- if (*s == e) {
- if (--cont == 0) return s+1;
- }
- else if (*s == b) cont++;
- }
- }
- return NULL; /* string ends out of balance */
-}
-
-
-static const char *max_expand (MatchState *ms, const char *s,
- const char *p, const char *ep) {
- ptrdiff_t i = 0; /* counts maximum expand for item */
- while (singlematch(ms, s + i, p, ep))
- i++;
- /* keeps trying to match with the maximum repetitions */
- while (i>=0) {
- const char *res = match(ms, (s+i), ep+1);
- if (res) return res;
- i--; /* else didn't match; reduce 1 repetition to try again */
- }
- return NULL;
-}
-
-
-static const char *min_expand (MatchState *ms, const char *s,
- const char *p, const char *ep) {
- for (;;) {
- const char *res = match(ms, s, ep+1);
- if (res != NULL)
- return res;
- else if (singlematch(ms, s, p, ep))
- s++; /* try with one more repetition */
- else return NULL;
- }
-}
-
-
-static const char *start_capture (MatchState *ms, const char *s,
- const char *p, int what) {
- const char *res;
- int level = ms->level;
- if (level >= LUA_MAXCAPTURES) luaL_error(ms->L, "too many captures");
- ms->capture[level].init = s;
- ms->capture[level].len = what;
- ms->level = level+1;
- if ((res=match(ms, s, p)) == NULL) /* match failed? */
- ms->level--; /* undo capture */
- return res;
-}
-
-
-static const char *end_capture (MatchState *ms, const char *s,
- const char *p) {
- int l = capture_to_close(ms);
- const char *res;
- ms->capture[l].len = s - ms->capture[l].init; /* close capture */
- if ((res = match(ms, s, p)) == NULL) /* match failed? */
- ms->capture[l].len = CAP_UNFINISHED; /* undo capture */
- return res;
-}
-
-
-static const char *match_capture (MatchState *ms, const char *s, int l) {
- size_t len;
- l = check_capture(ms, l);
- len = cast_sizet(ms->capture[l].len);
- if ((size_t)(ms->src_end-s) >= len &&
- memcmp(ms->capture[l].init, s, len) == 0)
- return s+len;
- else return NULL;
-}
-
-
-static const char *match (MatchState *ms, const char *s, const char *p) {
- if (l_unlikely(ms->matchdepth-- == 0))
- luaL_error(ms->L, "pattern too complex");
- init: /* using goto to optimize tail recursion */
- if (p != ms->p_end) { /* end of pattern? */
- switch (*p) {
- case '(': { /* start capture */
- if (*(p + 1) == ')') /* position capture? */
- s = start_capture(ms, s, p + 2, CAP_POSITION);
- else
- s = start_capture(ms, s, p + 1, CAP_UNFINISHED);
- break;
- }
- case ')': { /* end capture */
- s = end_capture(ms, s, p + 1);
- break;
- }
- case '$': {
- if ((p + 1) != ms->p_end) /* is the '$' the last char in pattern? */
- goto dflt; /* no; go to default */
- s = (s == ms->src_end) ? s : NULL; /* check end of string */
- break;
- }
- case L_ESC: { /* escaped sequences not in the format class[*+?-]? */
- switch (*(p + 1)) {
- case 'b': { /* balanced string? */
- s = matchbalance(ms, s, p + 2);
- if (s != NULL) {
- p += 4; goto init; /* return match(ms, s, p + 4); */
- } /* else fail (s == NULL) */
- break;
- }
- case 'f': { /* frontier? */
- const char *ep; char previous;
- p += 2;
- if (l_unlikely(*p != '['))
- luaL_error(ms->L, "missing '[' after '%%f' in pattern");
- ep = classend(ms, p); /* points to what is next */
- previous = (s == ms->src_init) ? '\0' : *(s - 1);
- if (!matchbracketclass(cast_uchar(previous), p, ep - 1) &&
- matchbracketclass(cast_uchar(*s), p, ep - 1)) {
- p = ep; goto init; /* return match(ms, s, ep); */
- }
- s = NULL; /* match failed */
- break;
- }
- case '0': case '1': case '2': case '3':
- case '4': case '5': case '6': case '7':
- case '8': case '9': { /* capture results (%0-%9)? */
- s = match_capture(ms, s, cast_uchar(*(p + 1)));
- if (s != NULL) {
- p += 2; goto init; /* return match(ms, s, p + 2) */
- }
- break;
- }
- default: goto dflt;
- }
- break;
- }
- default: dflt: { /* pattern class plus optional suffix */
- const char *ep = classend(ms, p); /* points to optional suffix */
- /* does not match at least once? */
- if (!singlematch(ms, s, p, ep)) {
- if (*ep == '*' || *ep == '?' || *ep == '-') { /* accept empty? */
- p = ep + 1; goto init; /* return match(ms, s, ep + 1); */
- }
- else /* '+' or no suffix */
- s = NULL; /* fail */
- }
- else { /* matched once */
- switch (*ep) { /* handle optional suffix */
- case '?': { /* optional */
- const char *res;
- if ((res = match(ms, s + 1, ep + 1)) != NULL)
- s = res;
- else {
- p = ep + 1; goto init; /* else return match(ms, s, ep + 1); */
- }
- break;
- }
- case '+': /* 1 or more repetitions */
- s++; /* 1 match already done */
- /* FALLTHROUGH */
- case '*': /* 0 or more repetitions */
- s = max_expand(ms, s, p, ep);
- break;
- case '-': /* 0 or more repetitions (minimum) */
- s = min_expand(ms, s, p, ep);
- break;
- default: /* no suffix */
- s++; p = ep; goto init; /* return match(ms, s + 1, ep); */
- }
- }
- break;
- }
- }
- }
- ms->matchdepth++;
- return s;
-}
-
-
-
-static const char *lmemfind (const char *s1, size_t l1,
- const char *s2, size_t l2) {
- if (l2 == 0) return s1; /* empty strings are everywhere */
- else if (l2 > l1) return NULL; /* avoids a negative 'l1' */
- else {
- const char *init; /* to search for a '*s2' inside 's1' */
- l2--; /* 1st char will be checked by 'memchr' */
- l1 = l1-l2; /* 's2' cannot be found after that */
- while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) {
- init++; /* 1st char is already checked */
- if (memcmp(init, s2+1, l2) == 0)
- return init-1;
- else { /* correct 'l1' and 's1' to try again */
- l1 -= ct_diff2sz(init - s1);
- s1 = init;
- }
- }
- return NULL; /* not found */
- }
-}
-
-
-/*
-** get information about the i-th capture. If there are no captures
-** and 'i==0', return information about the whole match, which
-** is the range 's'..'e'. If the capture is a string, return
-** its length and put its address in '*cap'. If it is an integer
-** (a position), push it on the stack and return CAP_POSITION.
-*/
-static ptrdiff_t get_onecapture (MatchState *ms, int i, const char *s,
- const char *e, const char **cap) {
- if (i >= ms->level) {
- if (l_unlikely(i != 0))
- luaL_error(ms->L, "invalid capture index %%%d", i + 1);
- *cap = s;
- return (e - s);
- }
- else {
- ptrdiff_t capl = ms->capture[i].len;
- *cap = ms->capture[i].init;
- if (l_unlikely(capl == CAP_UNFINISHED))
- luaL_error(ms->L, "unfinished capture");
- else if (capl == CAP_POSITION)
- lua_pushinteger(ms->L,
- ct_diff2S(ms->capture[i].init - ms->src_init) + 1);
- return capl;
- }
-}
-
-
-/*
-** Push the i-th capture on the stack.
-*/
-static void push_onecapture (MatchState *ms, int i, const char *s,
- const char *e) {
- const char *cap;
- ptrdiff_t l = get_onecapture(ms, i, s, e, &cap);
- if (l != CAP_POSITION)
- lua_pushlstring(ms->L, cap, cast_sizet(l));
- /* else position was already pushed */
-}
-
-
-static int push_captures (MatchState *ms, const char *s, const char *e) {
- int i;
- int nlevels = (ms->level == 0 && s) ? 1 : ms->level;
- luaL_checkstack(ms->L, nlevels, "too many captures");
- for (i = 0; i < nlevels; i++)
- push_onecapture(ms, i, s, e);
- return nlevels; /* number of strings pushed */
-}
-
-
-/* check whether pattern has no special characters */
-static int nospecials (const char *p, size_t l) {
- size_t upto = 0;
- do {
- if (strpbrk(p + upto, SPECIALS))
- return 0; /* pattern has a special character */
- upto += strlen(p + upto) + 1; /* may have more after \0 */
- } while (upto <= l);
- return 1; /* no special chars found */
-}
-
-
-static void prepstate (MatchState *ms, lua_State *L,
- const char *s, size_t ls, const char *p, size_t lp) {
- ms->L = L;
- ms->matchdepth = MAXCCALLS;
- ms->src_init = s;
- ms->src_end = s + ls;
- ms->p_end = p + lp;
-}
-
-
-static void reprepstate (MatchState *ms) {
- ms->level = 0;
- lua_assert(ms->matchdepth == MAXCCALLS);
-}
-
-
-static int str_find_aux (lua_State *L, int find) {
- size_t ls, lp;
- const char *s = luaL_checklstring(L, 1, &ls);
- const char *p = luaL_checklstring(L, 2, &lp);
- size_t init = posrelatI(luaL_optinteger(L, 3, 1), ls) - 1;
- if (init > ls) { /* start after string's end? */
- luaL_pushfail(L); /* cannot find anything */
- return 1;
- }
- /* explicit request or no special characters? */
- if (find && (lua_toboolean(L, 4) || nospecials(p, lp))) {
- /* do a plain search */
- const char *s2 = lmemfind(s + init, ls - init, p, lp);
- if (s2) {
- lua_pushinteger(L, ct_diff2S(s2 - s) + 1);
- lua_pushinteger(L, cast_st2S(ct_diff2sz(s2 - s) + lp));
- return 2;
- }
- }
- else {
- MatchState ms;
- const char *s1 = s + init;
- int anchor = (*p == '^');
- if (anchor) {
- p++; lp--; /* skip anchor character */
- }
- prepstate(&ms, L, s, ls, p, lp);
- do {
- const char *res;
- reprepstate(&ms);
- if ((res=match(&ms, s1, p)) != NULL) {
- if (find) {
- lua_pushinteger(L, ct_diff2S(s1 - s) + 1); /* start */
- lua_pushinteger(L, ct_diff2S(res - s)); /* end */
- return push_captures(&ms, NULL, 0) + 2;
- }
- else
- return push_captures(&ms, s1, res);
- }
- } while (s1++ < ms.src_end && !anchor);
- }
- luaL_pushfail(L); /* not found */
- return 1;
-}
-
-
-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);
-}
-
-
-/* state for 'gmatch' */
-typedef struct GMatchState {
- const char *src; /* current position */
- const char *p; /* pattern */
- const char *lastmatch; /* end of last match */
- MatchState ms; /* match state */
-} GMatchState;
-
-
-static int gmatch_aux (lua_State *L) {
- GMatchState *gm = (GMatchState *)lua_touserdata(L, lua_upvalueindex(3));
- const char *src;
- gm->ms.L = L;
- for (src = gm->src; src <= gm->ms.src_end; src++) {
- const char *e;
- reprepstate(&gm->ms);
- if ((e = match(&gm->ms, src, gm->p)) != NULL && e != gm->lastmatch) {
- gm->src = gm->lastmatch = e;
- return push_captures(&gm->ms, src, e);
- }
- }
- return 0; /* not found */
-}
-
-
-static int gmatch (lua_State *L) {
- size_t ls, lp;
- const char *s = luaL_checklstring(L, 1, &ls);
- const char *p = luaL_checklstring(L, 2, &lp);
- size_t init = posrelatI(luaL_optinteger(L, 3, 1), ls) - 1;
- GMatchState *gm;
- lua_settop(L, 2); /* keep strings on closure to avoid being collected */
- gm = (GMatchState *)lua_newuserdatauv(L, sizeof(GMatchState), 0);
- if (init > ls) /* start after string's end? */
- init = ls + 1; /* avoid overflows in 's + init' */
- prepstate(&gm->ms, L, s, ls, p, lp);
- gm->src = s + init; gm->p = p; gm->lastmatch = NULL;
- lua_pushcclosure(L, gmatch_aux, 3);
- return 1;
-}
-
-
-static void add_s (MatchState *ms, luaL_Buffer *b, const char *s,
- const char *e) {
- size_t l;
- lua_State *L = ms->L;
- const char *news = lua_tolstring(L, 3, &l);
- const char *p;
- while ((p = (char *)memchr(news, L_ESC, l)) != NULL) {
- luaL_addlstring(b, news, ct_diff2sz(p - news));
- p++; /* skip ESC */
- if (*p == L_ESC) /* '%%' */
- luaL_addchar(b, *p);
- else if (*p == '0') /* '%0' */
- luaL_addlstring(b, s, ct_diff2sz(e - s));
- else if (isdigit(cast_uchar(*p))) { /* '%n' */
- const char *cap;
- ptrdiff_t resl = get_onecapture(ms, *p - '1', s, e, &cap);
- if (resl == CAP_POSITION)
- luaL_addvalue(b); /* add position to accumulated result */
- else
- luaL_addlstring(b, cap, cast_sizet(resl));
- }
- else
- luaL_error(L, "invalid use of '%c' in replacement string", L_ESC);
- l -= ct_diff2sz(p + 1 - news);
- news = p + 1;
- }
- luaL_addlstring(b, news, l);
-}
-
-
-/*
-** Add the replacement value to the string buffer 'b'.
-** Return true if the original string was changed. (Function calls and
-** table indexing resulting in nil or false do not change the subject.)
-*/
-static int add_value (MatchState *ms, luaL_Buffer *b, const char *s,
- const char *e, int tr) {
- lua_State *L = ms->L;
- switch (tr) {
- case LUA_TFUNCTION: { /* call the function */
- int n;
- lua_pushvalue(L, 3); /* push the function */
- n = push_captures(ms, s, e); /* all captures as arguments */
- lua_call(L, n, 1); /* call it */
- break;
- }
- case LUA_TTABLE: { /* index the table */
- push_onecapture(ms, 0, s, e); /* first capture is the index */
- lua_gettable(L, 3);
- break;
- }
- default: { /* LUA_TNUMBER or LUA_TSTRING */
- add_s(ms, b, s, e); /* add value to the buffer */
- return 1; /* something changed */
- }
- }
- if (!lua_toboolean(L, -1)) { /* nil or false? */
- lua_pop(L, 1); /* remove value */
- luaL_addlstring(b, s, ct_diff2sz(e - s)); /* keep original text */
- return 0; /* no changes */
- }
- else if (l_unlikely(!lua_isstring(L, -1)))
- return luaL_error(L, "invalid replacement value (a %s)",
- luaL_typename(L, -1));
- else {
- luaL_addvalue(b); /* add result to accumulator */
- return 1; /* something changed */
- }
-}
-
-
-static int str_gsub (lua_State *L) {
- size_t srcl, lp;
- const char *src = luaL_checklstring(L, 1, &srcl); /* subject */
- const char *p = luaL_checklstring(L, 2, &lp); /* pattern */
- const char *lastmatch = NULL; /* end of last match */
- int tr = lua_type(L, 3); /* replacement type */
- /* max replacements */
- lua_Integer max_s = luaL_optinteger(L, 4, cast_st2S(srcl) + 1);
- int anchor = (*p == '^');
- lua_Integer n = 0; /* replacement count */
- int changed = 0; /* change flag */
- MatchState ms;
- luaL_Buffer b;
- luaL_argexpected(L, tr == LUA_TNUMBER || tr == LUA_TSTRING ||
- tr == LUA_TFUNCTION || tr == LUA_TTABLE, 3,
- "string/function/table");
- luaL_buffinit(L, &b);
- if (anchor) {
- p++; lp--; /* skip anchor character */
- }
- prepstate(&ms, L, src, srcl, p, lp);
- while (n < max_s) {
- const char *e;
- reprepstate(&ms); /* (re)prepare state for new match */
- if ((e = match(&ms, src, p)) != NULL && e != lastmatch) { /* match? */
- n++;
- changed = add_value(&ms, &b, src, e, tr) || changed;
- src = lastmatch = e;
- }
- else if (src < ms.src_end) /* otherwise, skip one character */
- luaL_addchar(&b, *src++);
- else break; /* end of subject */
- if (anchor) break;
- }
- if (!changed) /* no changes? */
- lua_pushvalue(L, 1); /* return original string */
- else { /* something changed */
- luaL_addlstring(&b, src, ct_diff2sz(ms.src_end - src));
- luaL_pushresult(&b); /* create and return new string */
- }
- lua_pushinteger(L, n); /* number of substitutions */
- return 2;
-}
-
-/* }====================================================== */
-
-
-
-/*
-** {======================================================
-** STRING FORMAT
-** =======================================================
-*/
-
-#if !defined(lua_number2strx) /* { */
-
-/*
-** Hexadecimal floating-point formatter
-*/
-
-#define SIZELENMOD (sizeof(LUA_NUMBER_FRMLEN)/sizeof(char))
-
-
-/*
-** Number of bits that goes into the first digit. It can be any value
-** between 1 and 4; the following definition tries to align the number
-** to nibble boundaries by making what is left after that first digit a
-** multiple of 4.
-*/
-#define L_NBFD ((l_floatatt(MANT_DIG) - 1)%4 + 1)
-
-
-/*
-** Add integer part of 'x' to buffer and return new 'x'
-*/
-static lua_Number adddigit (char *buff, unsigned n, lua_Number x) {
- lua_Number dd = l_mathop(floor)(x); /* get integer part from 'x' */
- int d = (int)dd;
- buff[n] = cast_char(d < 10 ? d + '0' : d - 10 + 'a'); /* add to buffer */
- return x - dd; /* return what is left */
-}
-
-
-static int num2straux (char *buff, unsigned sz, lua_Number x) {
- /* if 'inf' or 'NaN', format it like '%g' */
- if (x != x || x == (lua_Number)HUGE_VAL || x == -(lua_Number)HUGE_VAL)
- return l_sprintf(buff, sz, LUA_NUMBER_FMT, (LUAI_UACNUMBER)x);
- else if (x == 0) { /* can be -0... */
- /* create "0" or "-0" followed by exponent */
- return l_sprintf(buff, sz, LUA_NUMBER_FMT "x0p+0", (LUAI_UACNUMBER)x);
- }
- else {
- int e;
- lua_Number m = l_mathop(frexp)(x, &e); /* 'x' fraction and exponent */
- unsigned n = 0; /* character count */
- if (m < 0) { /* is number negative? */
- buff[n++] = '-'; /* add sign */
- m = -m; /* make it positive */
- }
- buff[n++] = '0'; buff[n++] = 'x'; /* add "0x" */
- m = adddigit(buff, n++, m * (1 << L_NBFD)); /* add first digit */
- e -= L_NBFD; /* this digit goes before the radix point */
- if (m > 0) { /* more digits? */
- buff[n++] = lua_getlocaledecpoint(); /* add radix point */
- do { /* add as many digits as needed */
- m = adddigit(buff, n++, m * 16);
- } while (m > 0);
- }
- n += cast_uint(l_sprintf(buff + n, sz - n, "p%+d", e)); /* add exponent */
- lua_assert(n < sz);
- return cast_int(n);
- }
-}
-
-
-static int lua_number2strx (lua_State *L, char *buff, unsigned sz,
- const char *fmt, lua_Number x) {
- int n = num2straux(buff, sz, x);
- if (fmt[SIZELENMOD] == 'A') {
- int i;
- for (i = 0; i < n; i++)
- buff[i] = cast_char(toupper(cast_uchar(buff[i])));
- }
- else if (l_unlikely(fmt[SIZELENMOD] != 'a'))
- return luaL_error(L, "modifiers for format '%%a'/'%%A' not implemented");
- return n;
-}
-
-#endif /* } */
-
-
-/*
-** Maximum size for items formatted with '%f'. This size is produced
-** by format('%.99f', -maxfloat), and is equal to 99 + 3 ('-', '.',
-** and '\0') + number of decimal digits to represent maxfloat (which
-** is maximum exponent + 1). (99+3+1, adding some extra, 110)
-*/
-#define MAX_ITEMF (110 + l_floatatt(MAX_10_EXP))
-
-
-/*
-** All formats except '%f' do not need that large limit. The other
-** float formats use exponents, so that they fit in the 99 limit for
-** significant digits; 's' for large strings and 'q' add items directly
-** to the buffer; all integer formats also fit in the 99 limit. The
-** worst case are floats: they may need 99 significant digits, plus
-** '0x', '-', '.', 'e+XXXX', and '\0'. Adding some extra, 120.
-*/
-#define MAX_ITEM 120
-
-
-/* valid flags in a format specification */
-#if !defined(L_FMTFLAGSF)
-
-/* valid flags for a, A, e, E, f, F, g, and G conversions */
-#define L_FMTFLAGSF "-+#0 "
-
-/* valid flags for o, x, and X conversions */
-#define L_FMTFLAGSX "-#0"
-
-/* valid flags for d and i conversions */
-#define L_FMTFLAGSI "-+0 "
-
-/* valid flags for u conversions */
-#define L_FMTFLAGSU "-0"
-
-/* valid flags for c, p, and s conversions */
-#define L_FMTFLAGSC "-"
-
-#endif
-
-
-/*
-** Maximum size of each format specification (such as "%-099.99d"):
-** Initial '%', flags (up to 5), width (2), period, precision (2),
-** length modifier (8), conversion specifier, and final '\0', plus some
-** extra.
-*/
-#define MAX_FORMAT 32
-
-
-static void addquoted (luaL_Buffer *b, const char *s, size_t len) {
- luaL_addchar(b, '"');
- while (len--) {
- if (*s == '"' || *s == '\\' || *s == '\n') {
- luaL_addchar(b, '\\');
- luaL_addchar(b, *s);
- }
- else if (iscntrl(cast_uchar(*s))) {
- char buff[10];
- if (!isdigit(cast_uchar(*(s+1))))
- l_sprintf(buff, sizeof(buff), "\\%d", (int)cast_uchar(*s));
- else
- l_sprintf(buff, sizeof(buff), "\\%03d", (int)cast_uchar(*s));
- luaL_addstring(b, buff);
- }
- else
- luaL_addchar(b, *s);
- s++;
- }
- luaL_addchar(b, '"');
-}
-
-
-/*
-** Serialize a floating-point number in such a way that it can be
-** scanned back by Lua. Use hexadecimal format for "common" numbers
-** (to preserve precision); inf, -inf, and NaN are handled separately.
-** (NaN cannot be expressed as a numeral, so we write '(0/0)' for it.)
-*/
-static int quotefloat (lua_State *L, char *buff, lua_Number n) {
- const char *s; /* for the fixed representations */
- if (n == (lua_Number)HUGE_VAL) /* inf? */
- s = "1e9999";
- else if (n == -(lua_Number)HUGE_VAL) /* -inf? */
- s = "-1e9999";
- else if (n != n) /* NaN? */
- s = "(0/0)";
- else { /* format number as hexadecimal */
- int nb = lua_number2strx(L, buff, MAX_ITEM,
- "%" LUA_NUMBER_FRMLEN "a", n);
- /* ensures that 'buff' string uses a dot as the radix character */
- if (memchr(buff, '.', cast_uint(nb)) == NULL) { /* no dot? */
- char point = lua_getlocaledecpoint(); /* try locale point */
- char *ppoint = (char *)memchr(buff, point, cast_uint(nb));
- if (ppoint) *ppoint = '.'; /* change it to a dot */
- }
- return nb;
- }
- /* for the fixed representations */
- return l_sprintf(buff, MAX_ITEM, "%s", s);
-}
-
-
-static void addliteral (lua_State *L, luaL_Buffer *b, int arg) {
- switch (lua_type(L, arg)) {
- case LUA_TSTRING: {
- size_t len;
- const char *s = lua_tolstring(L, arg, &len);
- addquoted(b, s, len);
- break;
- }
- case LUA_TNUMBER: {
- char *buff = luaL_prepbuffsize(b, MAX_ITEM);
- int nb;
- if (!lua_isinteger(L, arg)) /* float? */
- nb = quotefloat(L, buff, lua_tonumber(L, arg));
- else { /* integers */
- lua_Integer n = lua_tointeger(L, arg);
- const char *format = (n == LUA_MININTEGER) /* corner case? */
- ? "0x%" LUA_INTEGER_FRMLEN "x" /* use hex */
- : LUA_INTEGER_FMT; /* else use default format */
- nb = l_sprintf(buff, MAX_ITEM, format, (LUAI_UACINT)n);
- }
- luaL_addsize(b, cast_uint(nb));
- break;
- }
- case LUA_TNIL: case LUA_TBOOLEAN: {
- luaL_tolstring(L, arg, NULL);
- luaL_addvalue(b);
- break;
- }
- default: {
- luaL_argerror(L, arg, "value has no literal form");
- }
- }
-}
-
-
-static const char *get2digits (const char *s) {
- if (isdigit(cast_uchar(*s))) {
- s++;
- if (isdigit(cast_uchar(*s))) s++; /* (2 digits at most) */
- }
- return s;
-}
-
-
-/*
-** Check whether a conversion specification is valid. When called,
-** first character in 'form' must be '%' and last character must
-** be a valid conversion specifier. 'flags' are the accepted flags;
-** 'precision' signals whether to accept a precision.
-*/
-static void checkformat (lua_State *L, const char *form, const char *flags,
- int precision) {
- const char *spec = form + 1; /* skip '%' */
- spec += strspn(spec, flags); /* skip flags */
- if (*spec != '0') { /* a width cannot start with '0' */
- spec = get2digits(spec); /* skip width */
- if (*spec == '.' && precision) {
- spec++;
- spec = get2digits(spec); /* skip precision */
- }
- }
- if (!isalpha(cast_uchar(*spec))) /* did not go to the end? */
- luaL_error(L, "invalid conversion specification: '%s'", form);
-}
-
-
-/*
-** Get a conversion specification and copy it to 'form'.
-** Return the address of its last character.
-*/
-static const char *getformat (lua_State *L, const char *strfrmt,
- char *form) {
- /* spans flags, width, and precision ('0' is included as a flag) */
- size_t len = strspn(strfrmt, L_FMTFLAGSF "123456789.");
- len++; /* adds following character (should be the specifier) */
- /* still needs space for '%', '\0', plus a length modifier */
- if (len >= MAX_FORMAT - 10)
- luaL_error(L, "invalid format (too long)");
- *(form++) = '%';
- memcpy(form, strfrmt, len * sizeof(char));
- *(form + len) = '\0';
- return strfrmt + len - 1;
-}
-
-
-/*
-** add length modifier into formats
-*/
-static void addlenmod (char *form, const char *lenmod) {
- size_t l = strlen(form);
- size_t lm = strlen(lenmod);
- char spec = form[l - 1];
- strcpy(form + l - 1, lenmod);
- form[l + lm - 1] = spec;
- form[l + lm] = '\0';
-}
-
-
-static int str_format (lua_State *L) {
- int top = lua_gettop(L);
- int arg = 1;
- size_t sfl;
- const char *strfrmt = luaL_checklstring(L, arg, &sfl);
- const char *strfrmt_end = strfrmt+sfl;
- const char *flags;
- luaL_Buffer b;
- luaL_buffinit(L, &b);
- while (strfrmt < strfrmt_end) {
- if (*strfrmt != L_ESC)
- luaL_addchar(&b, *strfrmt++);
- else if (*++strfrmt == L_ESC)
- luaL_addchar(&b, *strfrmt++); /* %% */
- else { /* format item */
- char form[MAX_FORMAT]; /* to store the format ('%...') */
- unsigned maxitem = MAX_ITEM; /* maximum length for the result */
- char *buff = luaL_prepbuffsize(&b, maxitem); /* to put result */
- int nb = 0; /* number of bytes in result */
- if (++arg > top)
- return luaL_argerror(L, arg, "no value");
- strfrmt = getformat(L, strfrmt, form);
- switch (*strfrmt++) {
- case 'c': {
- checkformat(L, form, L_FMTFLAGSC, 0);
- nb = l_sprintf(buff, maxitem, form, (int)luaL_checkinteger(L, arg));
- break;
- }
- case 'd': case 'i':
- flags = L_FMTFLAGSI;
- goto intcase;
- case 'u':
- flags = L_FMTFLAGSU;
- goto intcase;
- case 'o': case 'x': case 'X':
- flags = L_FMTFLAGSX;
- intcase: {
- lua_Integer n = luaL_checkinteger(L, arg);
- checkformat(L, form, flags, 1);
- addlenmod(form, LUA_INTEGER_FRMLEN);
- nb = l_sprintf(buff, maxitem, form, (LUAI_UACINT)n);
- break;
- }
- case 'a': case 'A':
- checkformat(L, form, L_FMTFLAGSF, 1);
- addlenmod(form, LUA_NUMBER_FRMLEN);
- nb = lua_number2strx(L, buff, maxitem, form,
- luaL_checknumber(L, arg));
- break;
- case 'f':
- maxitem = MAX_ITEMF; /* extra space for '%f' */
- buff = luaL_prepbuffsize(&b, maxitem);
- /* FALLTHROUGH */
- case 'e': case 'E': case 'g': case 'G': {
- lua_Number n = luaL_checknumber(L, arg);
- checkformat(L, form, L_FMTFLAGSF, 1);
- addlenmod(form, LUA_NUMBER_FRMLEN);
- nb = l_sprintf(buff, maxitem, form, (LUAI_UACNUMBER)n);
- break;
- }
- case 'p': {
- const void *p = lua_topointer(L, arg);
- checkformat(L, form, L_FMTFLAGSC, 0);
- if (p == NULL) { /* avoid calling 'printf' with argument NULL */
- p = "(null)"; /* result */
- form[strlen(form) - 1] = 's'; /* format it as a string */
- }
- nb = l_sprintf(buff, maxitem, form, p);
- break;
- }
- case 'q': {
- if (form[2] != '\0') /* modifiers? */
- return luaL_error(L, "specifier '%%q' cannot have modifiers");
- addliteral(L, &b, arg);
- break;
- }
- case 's': {
- size_t l;
- const char *s = luaL_tolstring(L, arg, &l);
- if (form[2] == '\0') /* no modifiers? */
- luaL_addvalue(&b); /* keep entire string */
- else {
- luaL_argcheck(L, l == strlen(s), arg, "string contains zeros");
- checkformat(L, form, L_FMTFLAGSC, 1);
- if (strchr(form, '.') == NULL && l >= 100) {
- /* no precision and string is too long to be formatted */
- luaL_addvalue(&b); /* keep entire string */
- }
- else { /* format the string into 'buff' */
- nb = l_sprintf(buff, maxitem, form, s);
- lua_pop(L, 1); /* remove result from 'luaL_tolstring' */
- }
- }
- break;
- }
- default: { /* also treat cases 'pnLlh' */
- return luaL_error(L, "invalid conversion '%s' to 'format'", form);
- }
- }
- lua_assert(cast_uint(nb) < maxitem);
- luaL_addsize(&b, cast_uint(nb));
- }
- }
- luaL_pushresult(&b);
- return 1;
-}
-
-/* }====================================================== */
-
-
-/*
-** {======================================================
-** PACK/UNPACK
-** =======================================================
-*/
-
-
-/* value used for padding */
-#if !defined(LUAL_PACKPADBYTE)
-#define LUAL_PACKPADBYTE 0x00
-#endif
-
-/* maximum size for the binary representation of an integer */
-#define MAXINTSIZE 16
-
-/* number of bits in a character */
-#define NB CHAR_BIT
-
-/* mask for one character (NB 1's) */
-#define MC ((1 << NB) - 1)
-
-/* size of a lua_Integer */
-#define SZINT ((int)sizeof(lua_Integer))
-
-
-/* dummy union to get native endianness */
-static const union {
- int dummy;
- char little; /* true iff machine is little endian */
-} nativeendian = {1};
-
-
-/*
-** information to pack/unpack stuff
-*/
-typedef struct Header {
- lua_State *L;
- int islittle;
- unsigned maxalign;
-} Header;
-
-
-/*
-** options for pack/unpack
-*/
-typedef enum KOption {
- Kint, /* signed integers */
- Kuint, /* unsigned integers */
- Kfloat, /* single-precision floating-point numbers */
- Knumber, /* Lua "native" floating-point numbers */
- Kdouble, /* double-precision floating-point numbers */
- Kchar, /* fixed-length strings */
- Kstring, /* strings with prefixed length */
- Kzstr, /* zero-terminated strings */
- Kpadding, /* padding */
- Kpaddalign, /* padding for alignment */
- Knop /* no-op (configuration or spaces) */
-} KOption;
-
-
-/*
-** Read an integer numeral from string 'fmt' or return 'df' if
-** there is no numeral
-*/
-static int digit (int c) { return '0' <= c && c <= '9'; }
-
-static size_t getnum (const char **fmt, size_t df) {
- if (!digit(**fmt)) /* no number? */
- return df; /* return default value */
- else {
- size_t a = 0;
- do {
- a = a*10 + cast_uint(*((*fmt)++) - '0');
- } while (digit(**fmt) && a <= (MAX_SIZE - 9)/10);
- return a;
- }
-}
-
-
-/*
-** Read an integer numeral and raises an error if it is larger
-** than the maximum size of integers.
-*/
-static unsigned getnumlimit (Header *h, const char **fmt, size_t df) {
- size_t sz = getnum(fmt, df);
- if (l_unlikely((sz - 1u) >= MAXINTSIZE))
- return cast_uint(luaL_error(h->L,
- "integral size (%d) out of limits [1,%d]", sz, MAXINTSIZE));
- return cast_uint(sz);
-}
-
-
-/*
-** Initialize Header
-*/
-static void initheader (lua_State *L, Header *h) {
- h->L = L;
- h->islittle = nativeendian.little;
- h->maxalign = 1;
-}
-
-
-/*
-** Read and classify next option. 'size' is filled with option's size.
-*/
-static KOption getoption (Header *h, const char **fmt, size_t *size) {
- /* dummy structure to get native alignment requirements */
- struct cD { char c; union { LUAI_MAXALIGN; } u; };
- int opt = *((*fmt)++);
- *size = 0; /* default */
- switch (opt) {
- case 'b': *size = sizeof(char); return Kint;
- case 'B': *size = sizeof(char); return Kuint;
- case 'h': *size = sizeof(short); return Kint;
- case 'H': *size = sizeof(short); return Kuint;
- case 'l': *size = sizeof(long); return Kint;
- case 'L': *size = sizeof(long); return Kuint;
- case 'j': *size = sizeof(lua_Integer); return Kint;
- case 'J': *size = sizeof(lua_Integer); return Kuint;
- case 'T': *size = sizeof(size_t); return Kuint;
- case 'f': *size = sizeof(float); return Kfloat;
- case 'n': *size = sizeof(lua_Number); return Knumber;
- case 'd': *size = sizeof(double); return Kdouble;
- case 'i': *size = getnumlimit(h, fmt, sizeof(int)); return Kint;
- case 'I': *size = getnumlimit(h, fmt, sizeof(int)); return Kuint;
- case 's': *size = getnumlimit(h, fmt, sizeof(size_t)); return Kstring;
- case 'c':
- *size = getnum(fmt, cast_sizet(-1));
- if (l_unlikely(*size == cast_sizet(-1)))
- luaL_error(h->L, "missing size for format option 'c'");
- return Kchar;
- case 'z': return Kzstr;
- case 'x': *size = 1; return Kpadding;
- case 'X': return Kpaddalign;
- case ' ': break;
- case '<': h->islittle = 1; break;
- case '>': h->islittle = 0; break;
- case '=': h->islittle = nativeendian.little; break;
- case '!': {
- const size_t maxalign = offsetof(struct cD, u);
- h->maxalign = getnumlimit(h, fmt, maxalign);
- break;
- }
- default: luaL_error(h->L, "invalid format option '%c'", opt);
- }
- return Knop;
-}
-
-
-/*
-** Read, classify, and fill other details about the next option.
-** 'psize' is filled with option's size, 'notoalign' with its
-** alignment requirements.
-** Local variable 'size' gets the size to be aligned. (Kpadal option
-** always gets its full alignment, other options are limited by
-** the maximum alignment ('maxalign'). Kchar option needs no alignment
-** despite its size.
-*/
-static KOption getdetails (Header *h, size_t totalsize, const char **fmt,
- size_t *psize, unsigned *ntoalign) {
- KOption opt = getoption(h, fmt, psize);
- size_t align = *psize; /* usually, alignment follows size */
- if (opt == Kpaddalign) { /* 'X' gets alignment from following option */
- if (**fmt == '\0' || getoption(h, fmt, &align) == Kchar || align == 0)
- luaL_argerror(h->L, 1, "invalid next option for option 'X'");
- }
- if (align <= 1 || opt == Kchar) /* need no alignment? */
- *ntoalign = 0;
- else {
- if (align > h->maxalign) /* enforce maximum alignment */
- align = h->maxalign;
- if (l_unlikely(!ispow2(align))) { /* not a power of 2? */
- *ntoalign = 0; /* to avoid warnings */
- luaL_argerror(h->L, 1, "format asks for alignment not power of 2");
- }
- else {
- /* 'szmoda' = totalsize % align */
- unsigned szmoda = cast_uint(totalsize & (align - 1));
- *ntoalign = cast_uint((align - szmoda) & (align - 1));
- }
- }
- return opt;
-}
-
-
-/*
-** Pack integer 'n' with 'size' bytes and 'islittle' endianness.
-** The final 'if' handles the case when 'size' is larger than
-** the size of a Lua integer, correcting the extra sign-extension
-** bytes if necessary (by default they would be zeros).
-*/
-static void packint (luaL_Buffer *b, lua_Unsigned n,
- int islittle, unsigned size, int neg) {
- char *buff = luaL_prepbuffsize(b, size);
- unsigned i;
- buff[islittle ? 0 : size - 1] = (char)(n & MC); /* first byte */
- for (i = 1; i < size; i++) {
- n >>= NB;
- buff[islittle ? i : size - 1 - i] = (char)(n & MC);
- }
- if (neg && size > SZINT) { /* negative number need sign extension? */
- for (i = SZINT; i < size; i++) /* correct extra bytes */
- buff[islittle ? i : size - 1 - i] = (char)MC;
- }
- luaL_addsize(b, size); /* add result to buffer */
-}
-
-
-/*
-** Copy 'size' bytes from 'src' to 'dest', correcting endianness if
-** given 'islittle' is different from native endianness.
-*/
-static void copywithendian (char *dest, const char *src,
- unsigned size, int islittle) {
- if (islittle == nativeendian.little)
- memcpy(dest, src, size);
- else {
- dest += size - 1;
- while (size-- != 0)
- *(dest--) = *(src++);
- }
-}
-
-
-static int str_pack (lua_State *L) {
- luaL_Buffer b;
- Header h;
- const char *fmt = luaL_checkstring(L, 1); /* format string */
- int arg = 1; /* current argument to pack */
- size_t totalsize = 0; /* accumulate total size of result */
- initheader(L, &h);
- lua_pushnil(L); /* mark to separate arguments from string buffer */
- luaL_buffinit(L, &b);
- while (*fmt != '\0') {
- unsigned ntoalign;
- size_t size;
- KOption opt = getdetails(&h, totalsize, &fmt, &size, &ntoalign);
- luaL_argcheck(L, size + ntoalign <= MAX_SIZE - totalsize, arg,
- "result too long");
- totalsize += ntoalign + size;
- while (ntoalign-- > 0)
- luaL_addchar(&b, LUAL_PACKPADBYTE); /* fill alignment */
- arg++;
- switch (opt) {
- case Kint: { /* signed integers */
- lua_Integer n = luaL_checkinteger(L, arg);
- if (size < SZINT) { /* need overflow check? */
- lua_Integer lim = (lua_Integer)1 << ((size * NB) - 1);
- luaL_argcheck(L, -lim <= n && n < lim, arg, "integer overflow");
- }
- packint(&b, (lua_Unsigned)n, h.islittle, cast_uint(size), (n < 0));
- break;
- }
- case Kuint: { /* unsigned integers */
- lua_Integer n = luaL_checkinteger(L, arg);
- if (size < SZINT) /* need overflow check? */
- luaL_argcheck(L, (lua_Unsigned)n < ((lua_Unsigned)1 << (size * NB)),
- arg, "unsigned overflow");
- packint(&b, (lua_Unsigned)n, h.islittle, cast_uint(size), 0);
- break;
- }
- case Kfloat: { /* C float */
- float f = (float)luaL_checknumber(L, arg); /* get argument */
- char *buff = luaL_prepbuffsize(&b, sizeof(f));
- /* move 'f' to final result, correcting endianness if needed */
- copywithendian(buff, (char *)&f, sizeof(f), h.islittle);
- luaL_addsize(&b, size);
- break;
- }
- case Knumber: { /* Lua float */
- lua_Number f = luaL_checknumber(L, arg); /* get argument */
- char *buff = luaL_prepbuffsize(&b, sizeof(f));
- /* move 'f' to final result, correcting endianness if needed */
- copywithendian(buff, (char *)&f, sizeof(f), h.islittle);
- luaL_addsize(&b, size);
- break;
- }
- case Kdouble: { /* C double */
- double f = (double)luaL_checknumber(L, arg); /* get argument */
- char *buff = luaL_prepbuffsize(&b, sizeof(f));
- /* move 'f' to final result, correcting endianness if needed */
- copywithendian(buff, (char *)&f, sizeof(f), h.islittle);
- luaL_addsize(&b, size);
- break;
- }
- case Kchar: { /* fixed-size string */
- size_t len;
- const char *s = luaL_checklstring(L, arg, &len);
- luaL_argcheck(L, len <= size, arg, "string longer than given size");
- luaL_addlstring(&b, s, len); /* add string */
- if (len < size) { /* does it need padding? */
- size_t psize = size - len; /* pad size */
- char *buff = luaL_prepbuffsize(&b, psize);
- memset(buff, LUAL_PACKPADBYTE, psize);
- luaL_addsize(&b, psize);
- }
- break;
- }
- case Kstring: { /* strings with length count */
- size_t len;
- const char *s = luaL_checklstring(L, arg, &len);
- luaL_argcheck(L, size >= sizeof(lua_Unsigned) ||
- len < ((lua_Unsigned)1 << (size * NB)),
- arg, "string length does not fit in given size");
- /* pack length */
- packint(&b, (lua_Unsigned)len, h.islittle, cast_uint(size), 0);
- luaL_addlstring(&b, s, len);
- totalsize += len;
- break;
- }
- case Kzstr: { /* zero-terminated string */
- size_t len;
- const char *s = luaL_checklstring(L, arg, &len);
- luaL_argcheck(L, strlen(s) == len, arg, "string contains zeros");
- luaL_addlstring(&b, s, len);
- luaL_addchar(&b, '\0'); /* add zero at the end */
- totalsize += len + 1;
- break;
- }
- case Kpadding: luaL_addchar(&b, LUAL_PACKPADBYTE); /* FALLTHROUGH */
- case Kpaddalign: case Knop:
- arg--; /* undo increment */
- break;
- }
- }
- luaL_pushresult(&b);
- return 1;
-}
-
-
-static int str_packsize (lua_State *L) {
- Header h;
- const char *fmt = luaL_checkstring(L, 1); /* format string */
- size_t totalsize = 0; /* accumulate total size of result */
- initheader(L, &h);
- while (*fmt != '\0') {
- unsigned ntoalign;
- size_t size;
- KOption opt = getdetails(&h, totalsize, &fmt, &size, &ntoalign);
- luaL_argcheck(L, opt != Kstring && opt != Kzstr, 1,
- "variable-length format");
- size += ntoalign; /* total space used by option */
- luaL_argcheck(L, totalsize <= MAX_SIZE - size,
- 1, "format result too large");
- totalsize += size;
- }
- lua_pushinteger(L, cast_st2S(totalsize));
- return 1;
-}
-
-
-/*
-** Unpack an integer with 'size' bytes and 'islittle' endianness.
-** If size is smaller than the size of a Lua integer and integer
-** is signed, must do sign extension (propagating the sign to the
-** higher bits); if size is larger than the size of a Lua integer,
-** it must check the unread bytes to see whether they do not cause an
-** overflow.
-*/
-static lua_Integer unpackint (lua_State *L, const char *str,
- int islittle, int size, int issigned) {
- lua_Unsigned res = 0;
- int i;
- int limit = (size <= SZINT) ? size : SZINT;
- for (i = limit - 1; i >= 0; i--) {
- res <<= NB;
- res |= (lua_Unsigned)(unsigned char)str[islittle ? i : size - 1 - i];
- }
- if (size < SZINT) { /* real size smaller than lua_Integer? */
- if (issigned) { /* needs sign extension? */
- lua_Unsigned mask = (lua_Unsigned)1 << (size*NB - 1);
- res = ((res ^ mask) - mask); /* do sign extension */
- }
- }
- else if (size > SZINT) { /* must check unread bytes */
- int mask = (!issigned || (lua_Integer)res >= 0) ? 0 : MC;
- for (i = limit; i < size; i++) {
- if (l_unlikely((unsigned char)str[islittle ? i : size - 1 - i] != mask))
- luaL_error(L, "%d-byte integer does not fit into Lua Integer", size);
- }
- }
- return (lua_Integer)res;
-}
-
-
-static int str_unpack (lua_State *L) {
- Header h;
- const char *fmt = luaL_checkstring(L, 1);
- size_t ld;
- const char *data = luaL_checklstring(L, 2, &ld);
- size_t pos = posrelatI(luaL_optinteger(L, 3, 1), ld) - 1;
- int n = 0; /* number of results */
- luaL_argcheck(L, pos <= ld, 3, "initial position out of string");
- initheader(L, &h);
- while (*fmt != '\0') {
- unsigned ntoalign;
- size_t size;
- KOption opt = getdetails(&h, pos, &fmt, &size, &ntoalign);
- luaL_argcheck(L, ntoalign + size <= ld - pos, 2,
- "data string too short");
- pos += ntoalign; /* skip alignment */
- /* stack space for item + next position */
- luaL_checkstack(L, 2, "too many results");
- n++;
- switch (opt) {
- case Kint:
- case Kuint: {
- lua_Integer res = unpackint(L, data + pos, h.islittle,
- cast_int(size), (opt == Kint));
- lua_pushinteger(L, res);
- break;
- }
- case Kfloat: {
- float f;
- copywithendian((char *)&f, data + pos, sizeof(f), h.islittle);
- lua_pushnumber(L, (lua_Number)f);
- break;
- }
- case Knumber: {
- lua_Number f;
- copywithendian((char *)&f, data + pos, sizeof(f), h.islittle);
- lua_pushnumber(L, f);
- break;
- }
- case Kdouble: {
- double f;
- copywithendian((char *)&f, data + pos, sizeof(f), h.islittle);
- lua_pushnumber(L, (lua_Number)f);
- break;
- }
- case Kchar: {
- lua_pushlstring(L, data + pos, size);
- break;
- }
- case Kstring: {
- lua_Unsigned len = (lua_Unsigned)unpackint(L, data + pos,
- h.islittle, cast_int(size), 0);
- luaL_argcheck(L, len <= ld - pos - size, 2, "data string too short");
- lua_pushlstring(L, data + pos + size, cast_sizet(len));
- pos += cast_sizet(len); /* skip string */
- break;
- }
- case Kzstr: {
- size_t len = strlen(data + pos);
- luaL_argcheck(L, pos + len < ld, 2,
- "unfinished string for format 'z'");
- lua_pushlstring(L, data + pos, len);
- pos += len + 1; /* skip string plus final '\0' */
- break;
- }
- case Kpaddalign: case Kpadding: case Knop:
- n--; /* undo increment */
- break;
- }
- pos += size;
- }
- lua_pushinteger(L, cast_st2S(pos) + 1); /* next position */
- return n + 1;
-}
-
-/* }====================================================== */
-
-
-static const luaL_Reg strlib[] = {
- {"byte", str_byte},
- {"char", str_char},
- {"dump", str_dump},
- {"find", str_find},
- {"format", str_format},
- {"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},
- {"pack", str_pack},
- {"packsize", str_packsize},
- {"unpack", str_unpack},
- {NULL, NULL}
-};
-
-
-static void createmetatable (lua_State *L) {
- /* table to be metatable for strings */
- luaL_newlibtable(L, stringmetamethods);
- luaL_setfuncs(L, stringmetamethods, 0);
- lua_pushliteral(L, ""); /* dummy string */
- lua_pushvalue(L, -2); /* copy table */
- lua_setmetatable(L, -2); /* set table as metatable for strings */
- lua_pop(L, 1); /* pop dummy string */
- lua_pushvalue(L, -2); /* get string library */
- lua_setfield(L, -2, "__index"); /* metatable.__index = string */
- lua_pop(L, 1); /* pop metatable */
-}
-
-
-/*
-** Open string library
-*/
-LUAMOD_API int luaopen_string (lua_State *L) {
- luaL_newlib(L, strlib);
- createmetatable(L);
- return 1;
-}
-
diff --git a/ltable.c b/ltable.c
deleted file mode 100644
index 2f2b5c1f5c..0000000000
--- a/ltable.c
+++ /dev/null
@@ -1,1355 +0,0 @@
-/*
-** $Id: ltable.c $
-** Lua tables (hash)
-** See Copyright Notice in lua.h
-*/
-
-#define ltable_c
-#define LUA_CORE
-
-#include "lprefix.h"
-
-
-/*
-** Implementation of tables (aka arrays, objects, or hash tables).
-** Tables keep its elements in two parts: an array part and a hash part.
-** Non-negative integer keys are all candidates to be kept in the array
-** part. The actual size of the array is the largest 'n' such that
-** more than half the slots between 1 and n are in use.
-** Hash uses a mix of chained scatter table with Brent's variation.
-** A main invariant of these tables is that, if an element is not
-** in its main position (i.e. the 'original' position that its hash gives
-** to it), then the colliding element is in its own main position.
-** Hence even when the load factor reaches 100%, performance remains good.
-*/
-
-#include
-#include
-#include
-
-#include "lua.h"
-
-#include "ldebug.h"
-#include "ldo.h"
-#include "lgc.h"
-#include "lmem.h"
-#include "lobject.h"
-#include "lstate.h"
-#include "lstring.h"
-#include "ltable.h"
-#include "lvm.h"
-
-
-/*
-** Only hash parts with at least 2^LIMFORLAST have a 'lastfree' field
-** that optimizes finding a free slot. That field is stored just before
-** the array of nodes, in the same block. Smaller tables do a complete
-** search when looking for a free slot.
-*/
-#define LIMFORLAST 3 /* log2 of real limit (8) */
-
-/*
-** The union 'Limbox' stores 'lastfree' and ensures that what follows it
-** is properly aligned to store a Node.
-*/
-typedef struct { Node *dummy; Node follows_pNode; } Limbox_aux;
-
-typedef union {
- Node *lastfree;
- char padding[offsetof(Limbox_aux, follows_pNode)];
-} Limbox;
-
-#define haslastfree(t) ((t)->lsizenode >= LIMFORLAST)
-#define getlastfree(t) ((cast(Limbox *, (t)->node) - 1)->lastfree)
-
-
-/*
-** MAXABITS is the largest integer such that 2^MAXABITS fits in an
-** unsigned int.
-*/
-#define MAXABITS (l_numbits(int) - 1)
-
-
-/*
-** MAXASIZEB is the maximum number of elements in the array part such
-** that the size of the array fits in 'size_t'.
-*/
-#define MAXASIZEB (MAX_SIZET/(sizeof(Value) + 1))
-
-
-/*
-** MAXASIZE is the maximum size of the array part. It is the minimum
-** between 2^MAXABITS and MAXASIZEB.
-*/
-#define MAXASIZE \
- (((1u << MAXABITS) < MAXASIZEB) ? (1u << MAXABITS) : cast_uint(MAXASIZEB))
-
-/*
-** MAXHBITS is the largest integer such that 2^MAXHBITS fits in a
-** signed int.
-*/
-#define MAXHBITS (MAXABITS - 1)
-
-
-/*
-** MAXHSIZE is the maximum size of the hash part. It is the minimum
-** between 2^MAXHBITS and the maximum size such that, measured in bytes,
-** it fits in a 'size_t'.
-*/
-#define MAXHSIZE luaM_limitN(1 << MAXHBITS, Node)
-
-
-/*
-** When the original hash value is good, hashing by a power of 2
-** avoids the cost of '%'.
-*/
-#define hashpow2(t,n) (gnode(t, lmod((n), sizenode(t))))
-
-/*
-** for other types, it is better to avoid modulo by power of 2, as
-** they can have many 2 factors.
-*/
-#define hashmod(t,n) (gnode(t, ((n) % ((sizenode(t)-1u)|1u))))
-
-
-#define hashstr(t,str) hashpow2(t, (str)->hash)
-#define hashboolean(t,p) hashpow2(t, p)
-
-
-#define hashpointer(t,p) hashmod(t, point2uint(p))
-
-
-#define dummynode (&dummynode_)
-
-/*
-** Common hash part for tables with empty hash parts. That allows all
-** tables to have a hash part, avoiding an extra check ("is there a hash
-** part?") when indexing. Its sole node has an empty value and a key
-** (DEADKEY, NULL) that is different from any valid TValue.
-*/
-static const Node dummynode_ = {
- {{NULL}, LUA_VEMPTY, /* value's value and type */
- LUA_TDEADKEY, 0, {NULL}} /* key type, next, and key value */
-};
-
-
-static const TValue absentkey = {ABSTKEYCONSTANT};
-
-
-/*
-** Hash for integers. To allow a good hash, use the remainder operator
-** ('%'). If integer fits as a non-negative int, compute an int
-** remainder, which is faster. Otherwise, use an unsigned-integer
-** remainder, which uses all bits and ensures a non-negative result.
-*/
-static Node *hashint (const Table *t, lua_Integer i) {
- lua_Unsigned ui = l_castS2U(i);
- if (ui <= cast_uint(INT_MAX))
- return gnode(t, cast_int(ui) % cast_int((sizenode(t)-1) | 1));
- else
- return hashmod(t, ui);
-}
-
-
-/*
-** Hash for floating-point numbers.
-** The main computation should be just
-** n = frexp(n, &i); return (n * INT_MAX) + i
-** but there are some numerical subtleties.
-** In a two-complement representation, INT_MAX may not have an exact
-** representation as a float, but INT_MIN does; because the absolute
-** value of 'frexp' is smaller than 1 (unless 'n' is inf/NaN), the
-** absolute value of the product 'frexp * -INT_MIN' is smaller or equal
-** to INT_MAX. Next, the use of 'unsigned int' avoids overflows when
-** adding 'i'; the use of '~u' (instead of '-u') avoids problems with
-** INT_MIN.
-*/
-#if !defined(l_hashfloat)
-static unsigned l_hashfloat (lua_Number n) {
- int i;
- lua_Integer ni;
- n = l_mathop(frexp)(n, &i) * -cast_num(INT_MIN);
- if (!lua_numbertointeger(n, &ni)) { /* is 'n' inf/-inf/NaN? */
- lua_assert(luai_numisnan(n) || l_mathop(fabs)(n) == cast_num(HUGE_VAL));
- return 0;
- }
- else { /* normal case */
- unsigned int u = cast_uint(i) + cast_uint(ni);
- return (u <= cast_uint(INT_MAX) ? u : ~u);
- }
-}
-#endif
-
-
-/*
-** returns the 'main' position of an element in a table (that is,
-** the index of its hash value).
-*/
-static Node *mainpositionTV (const Table *t, const TValue *key) {
- switch (ttypetag(key)) {
- case LUA_VNUMINT: {
- lua_Integer i = ivalue(key);
- return hashint(t, i);
- }
- case LUA_VNUMFLT: {
- lua_Number n = fltvalue(key);
- return hashmod(t, l_hashfloat(n));
- }
- case LUA_VSHRSTR: {
- TString *ts = tsvalue(key);
- return hashstr(t, ts);
- }
- case LUA_VLNGSTR: {
- TString *ts = tsvalue(key);
- return hashpow2(t, luaS_hashlongstr(ts));
- }
- case LUA_VFALSE:
- return hashboolean(t, 0);
- case LUA_VTRUE:
- return hashboolean(t, 1);
- case LUA_VLIGHTUSERDATA: {
- void *p = pvalue(key);
- return hashpointer(t, p);
- }
- case LUA_VLCF: {
- lua_CFunction f = fvalue(key);
- return hashpointer(t, f);
- }
- default: {
- GCObject *o = gcvalue(key);
- return hashpointer(t, o);
- }
- }
-}
-
-
-l_sinline Node *mainpositionfromnode (const Table *t, Node *nd) {
- TValue key;
- getnodekey(cast(lua_State *, NULL), &key, nd);
- return mainpositionTV(t, &key);
-}
-
-
-/*
-** Check whether key 'k1' is equal to the key in node 'n2'. This
-** equality is raw, so there are no metamethods. Floats with integer
-** values have been normalized, so integers cannot be equal to
-** floats. It is assumed that 'eqshrstr' is simply pointer equality,
-** so that short strings are handled in the default case. The flag
-** 'deadok' means to accept dead keys as equal to their original values.
-** (Only collectable objects can produce dead keys.) Note that dead
-** long strings are also compared by identity. Once a key is dead,
-** its corresponding value may be collected, and then another value
-** can be created with the same address. If this other value is given
-** to 'next', 'equalkey' will signal a false positive. In a regular
-** traversal, this situation should never happen, as all keys given to
-** 'next' came from the table itself, and therefore could not have been
-** collected. Outside a regular traversal, we have garbage in, garbage
-** out. What is relevant is that this false positive does not break
-** anything. (In particular, 'next' will return some other valid item
-** on the table or nil.)
-*/
-static int equalkey (const TValue *k1, const Node *n2, int deadok) {
- if (rawtt(k1) != keytt(n2)) { /* not the same variants? */
- if (keyisshrstr(n2) && ttislngstring(k1)) {
- /* an external string can be equal to a short-string key */
- return luaS_eqstr(tsvalue(k1), keystrval(n2));
- }
- else if (deadok && keyisdead(n2) && iscollectable(k1)) {
- /* a collectable value can be equal to a dead key */
- return gcvalue(k1) == gcvalueraw(keyval(n2));
- }
- else
- return 0; /* otherwise, different variants cannot be equal */
- }
- else { /* equal variants */
- switch (keytt(n2)) {
- case LUA_VNIL: case LUA_VFALSE: case LUA_VTRUE:
- return 1;
- case LUA_VNUMINT:
- return (ivalue(k1) == keyival(n2));
- case LUA_VNUMFLT:
- return luai_numeq(fltvalue(k1), fltvalueraw(keyval(n2)));
- case LUA_VLIGHTUSERDATA:
- return pvalue(k1) == pvalueraw(keyval(n2));
- case LUA_VLCF:
- return fvalue(k1) == fvalueraw(keyval(n2));
- case ctb(LUA_VLNGSTR):
- return luaS_eqstr(tsvalue(k1), keystrval(n2));
- default:
- return gcvalue(k1) == gcvalueraw(keyval(n2));
- }
- }
-}
-
-
-/*
-** "Generic" get version. (Not that generic: not valid for integers,
-** which may be in array part, nor for floats with integral values.)
-** See explanation about 'deadok' in function 'equalkey'.
-*/
-static const TValue *getgeneric (Table *t, const TValue *key, int deadok) {
- Node *n = mainpositionTV(t, key);
- for (;;) { /* check whether 'key' is somewhere in the chain */
- if (equalkey(key, n, deadok))
- return gval(n); /* that's it */
- else {
- int nx = gnext(n);
- if (nx == 0)
- return &absentkey; /* not found */
- n += nx;
- }
- }
-}
-
-
-/*
-** Return the index 'k' (converted to an unsigned) if it is inside
-** the range [1, limit].
-*/
-static unsigned checkrange (lua_Integer k, unsigned limit) {
- return (l_castS2U(k) - 1u < limit) ? cast_uint(k) : 0;
-}
-
-
-/*
-** Return the index 'k' if 'k' is an appropriate key to live in the
-** array part of a table, 0 otherwise.
-*/
-#define arrayindex(k) checkrange(k, MAXASIZE)
-
-
-/*
-** Check whether an integer key is in the array part of a table and
-** return its index there, or zero.
-*/
-#define ikeyinarray(t,k) checkrange(k, t->asize)
-
-
-/*
-** Check whether a key is in the array part of a table and return its
-** index there, or zero.
-*/
-static unsigned keyinarray (Table *t, const TValue *key) {
- return (ttisinteger(key)) ? ikeyinarray(t, ivalue(key)) : 0;
-}
-
-
-/*
-** returns the index of a 'key' for table traversals. First goes all
-** elements in the array part, then elements in the hash part. The
-** beginning of a traversal is signaled by 0.
-*/
-static unsigned findindex (lua_State *L, Table *t, TValue *key,
- unsigned asize) {
- unsigned int i;
- if (ttisnil(key)) return 0; /* first iteration */
- i = keyinarray(t, key);
- if (i != 0) /* is 'key' inside array part? */
- return i; /* yes; that's the index */
- else {
- const TValue *n = getgeneric(t, key, 1);
- if (l_unlikely(isabstkey(n)))
- luaG_runerror(L, "invalid key to 'next'"); /* key not found */
- i = cast_uint(nodefromval(n) - gnode(t, 0)); /* key index in hash table */
- /* hash elements are numbered after array ones */
- return (i + 1) + asize;
- }
-}
-
-
-int luaH_next (lua_State *L, Table *t, StkId key) {
- unsigned int asize = t->asize;
- unsigned int i = findindex(L, t, s2v(key), asize); /* find original key */
- for (; i < asize; i++) { /* try first array part */
- lu_byte tag = *getArrTag(t, i);
- if (!tagisempty(tag)) { /* a non-empty entry? */
- setivalue(s2v(key), cast_int(i) + 1);
- farr2val(t, i, tag, s2v(key + 1));
- return 1;
- }
- }
- for (i -= asize; i < sizenode(t); i++) { /* hash part */
- if (!isempty(gval(gnode(t, i)))) { /* a non-empty entry? */
- Node *n = gnode(t, i);
- getnodekey(L, s2v(key), n);
- setobj2s(L, key + 1, gval(n));
- return 1;
- }
- }
- return 0; /* no more elements */
-}
-
-
-/* Extra space in Node array if it has a lastfree entry */
-#define extraLastfree(t) (haslastfree(t) ? sizeof(Limbox) : 0)
-
-/* 'node' size in bytes */
-static size_t sizehash (Table *t) {
- return cast_sizet(sizenode(t)) * sizeof(Node) + extraLastfree(t);
-}
-
-
-static void freehash (lua_State *L, Table *t) {
- if (!isdummy(t)) {
- /* get pointer to the beginning of Node array */
- char *arr = cast_charp(t->node) - extraLastfree(t);
- luaM_freearray(L, arr, sizehash(t));
- }
-}
-
-
-/*
-** {=============================================================
-** Rehash
-** ==============================================================
-*/
-
-static int insertkey (Table *t, const TValue *key, TValue *value);
-static void newcheckedkey (Table *t, const TValue *key, TValue *value);
-
-
-/*
-** Structure to count the keys in a table.
-** 'total' is the total number of keys in the table.
-** 'na' is the number of *array indices* in the table (see 'arrayindex').
-** 'deleted' is true if there are deleted nodes in the hash part.
-** 'nums' is a "count array" where 'nums[i]' is the number of integer
-** keys between 2^(i - 1) + 1 and 2^i. Note that 'na' is the summation
-** of 'nums'.
-*/
-typedef struct {
- unsigned total;
- unsigned na;
- int deleted;
- unsigned nums[MAXABITS + 1];
-} Counters;
-
-
-/*
-** Check whether it is worth to use 'na' array entries instead of 'nh'
-** hash nodes. (A hash node uses ~3 times more memory than an array
-** entry: Two values plus 'next' versus one value.) Evaluate with size_t
-** to avoid overflows.
-*/
-#define arrayXhash(na,nh) (cast_sizet(na) <= cast_sizet(nh) * 3)
-
-/*
-** Compute the optimal size for the array part of table 't'.
-** This size maximizes the number of elements going to the array part
-** while satisfying the condition 'arrayXhash' with the use of memory if
-** all those elements went to the hash part.
-** 'ct->na' enters with the total number of array indices in the table
-** and leaves with the number of keys that will go to the array part;
-** return the optimal size for the array part.
-*/
-static unsigned computesizes (Counters *ct) {
- int i;
- unsigned int twotoi; /* 2^i (candidate for optimal size) */
- unsigned int a = 0; /* number of elements smaller than 2^i */
- unsigned int na = 0; /* number of elements to go to array part */
- unsigned int optimal = 0; /* optimal size for array part */
- /* traverse slices while 'twotoi' does not overflow and total of array
- indices still can satisfy 'arrayXhash' against the array size */
- for (i = 0, twotoi = 1;
- twotoi > 0 && arrayXhash(twotoi, ct->na);
- i++, twotoi *= 2) {
- unsigned nums = ct->nums[i];
- a += nums;
- if (nums > 0 && /* grows array only if it gets more elements... */
- arrayXhash(twotoi, a)) { /* ...while using "less memory" */
- optimal = twotoi; /* optimal size (till now) */
- na = a; /* all elements up to 'optimal' will go to array part */
- }
- }
- ct->na = na;
- return optimal;
-}
-
-
-static void countint (lua_Integer key, Counters *ct) {
- unsigned int k = arrayindex(key);
- if (k != 0) { /* is 'key' an array index? */
- ct->nums[luaO_ceillog2(k)]++; /* count as such */
- ct->na++;
- }
-}
-
-
-l_sinline int arraykeyisempty (const Table *t, unsigned key) {
- int tag = *getArrTag(t, key - 1);
- return tagisempty(tag);
-}
-
-
-/*
-** Count keys in array part of table 't'.
-*/
-static void numusearray (const Table *t, Counters *ct) {
- int lg;
- unsigned int ttlg; /* 2^lg */
- unsigned int ause = 0; /* summation of 'nums' */
- unsigned int i = 1; /* index to traverse all array keys */
- unsigned int asize = t->asize;
- /* traverse each slice */
- for (lg = 0, ttlg = 1; lg <= MAXABITS; lg++, ttlg *= 2) {
- unsigned int lc = 0; /* counter */
- unsigned int lim = ttlg;
- if (lim > asize) {
- lim = asize; /* adjust upper limit */
- if (i > lim)
- break; /* no more elements to count */
- }
- /* count elements in range (2^(lg - 1), 2^lg] */
- for (; i <= lim; i++) {
- if (!arraykeyisempty(t, i))
- lc++;
- }
- ct->nums[lg] += lc;
- ause += lc;
- }
- ct->total += ause;
- ct->na += ause;
-}
-
-
-/*
-** Count keys in hash part of table 't'. As this only happens during
-** a rehash, all nodes have been used. A node can have a nil value only
-** if it was deleted after being created.
-*/
-static void numusehash (const Table *t, Counters *ct) {
- unsigned i = sizenode(t);
- unsigned total = 0;
- while (i--) {
- Node *n = &t->node[i];
- if (isempty(gval(n))) {
- lua_assert(!keyisnil(n)); /* entry was deleted; key cannot be nil */
- ct->deleted = 1;
- }
- else {
- total++;
- if (keyisinteger(n))
- countint(keyival(n), ct);
- }
- }
- ct->total += total;
-}
-
-
-/*
-** Convert an "abstract size" (number of slots in an array) to
-** "concrete size" (number of bytes in the array).
-*/
-static size_t concretesize (unsigned int size) {
- if (size == 0)
- return 0;
- else /* space for the two arrays plus an unsigned in between */
- return size * (sizeof(Value) + 1) + sizeof(unsigned);
-}
-
-
-/*
-** Resize the array part of a table. If new size is equal to the old,
-** do nothing. Else, if new size is zero, free the old array. (It must
-** be present, as the sizes are different.) Otherwise, allocate a new
-** array, move the common elements to new proper position, and then
-** frees the old array.
-** We could reallocate the array, but we still would need to move the
-** elements to their new position, so the copy implicit in realloc is a
-** waste. Moreover, most allocators will move the array anyway when the
-** new size is double the old one (the most common case).
-*/
-static Value *resizearray (lua_State *L , Table *t,
- unsigned oldasize,
- unsigned newasize) {
- if (oldasize == newasize)
- return t->array; /* nothing to be done */
- else if (newasize == 0) { /* erasing array? */
- Value *op = t->array - oldasize; /* original array's real address */
- luaM_freemem(L, op, concretesize(oldasize)); /* free it */
- return NULL;
- }
- else {
- size_t newasizeb = concretesize(newasize);
- Value *np = cast(Value *,
- luaM_reallocvector(L, NULL, 0, newasizeb, lu_byte));
- if (np == NULL) /* allocation error? */
- return NULL;
- np += newasize; /* shift pointer to the end of value segment */
- if (oldasize > 0) {
- /* move common elements to new position */
- size_t oldasizeb = concretesize(oldasize);
- Value *op = t->array; /* original array */
- unsigned tomove = (oldasize < newasize) ? oldasize : newasize;
- size_t tomoveb = (oldasize < newasize) ? oldasizeb : newasizeb;
- lua_assert(tomoveb > 0);
- memcpy(np - tomove, op - tomove, tomoveb);
- luaM_freemem(L, op - oldasize, oldasizeb); /* free old block */
- }
- return np;
- }
-}
-
-
-/*
-** Creates an array for the hash part of a table with the given
-** size, or reuses the dummy node if size is zero.
-** The computation for size overflow is in two steps: the first
-** comparison ensures that the shift in the second one does not
-** overflow.
-*/
-static void setnodevector (lua_State *L, Table *t, unsigned size) {
- if (size == 0) { /* no elements to hash part? */
- t->node = cast(Node *, dummynode); /* use common 'dummynode' */
- t->lsizenode = 0;
- setdummy(t); /* signal that it is using dummy node */
- }
- else {
- int i;
- int lsize = luaO_ceillog2(size);
- if (lsize > MAXHBITS || (1 << lsize) > MAXHSIZE)
- luaG_runerror(L, "table overflow");
- size = twoto(lsize);
- if (lsize < LIMFORLAST) /* no 'lastfree' field? */
- t->node = luaM_newvector(L, size, Node);
- else {
- size_t bsize = size * sizeof(Node) + sizeof(Limbox);
- char *node = luaM_newblock(L, bsize);
- t->node = cast(Node *, node + sizeof(Limbox));
- getlastfree(t) = gnode(t, size); /* all positions are free */
- }
- t->lsizenode = cast_byte(lsize);
- setnodummy(t);
- for (i = 0; i < cast_int(size); i++) {
- Node *n = gnode(t, i);
- gnext(n) = 0;
- setnilkey(n);
- setempty(gval(n));
- }
- }
-}
-
-
-/*
-** (Re)insert all elements from the hash part of 'ot' into table 't'.
-*/
-static void reinserthash (lua_State *L, Table *ot, Table *t) {
- unsigned j;
- unsigned size = sizenode(ot);
- for (j = 0; j < size; j++) {
- Node *old = gnode(ot, j);
- if (!isempty(gval(old))) {
- /* doesn't need barrier/invalidate cache, as entry was
- already present in the table */
- TValue k;
- getnodekey(L, &k, old);
- newcheckedkey(t, &k, gval(old));
- }
- }
-}
-
-
-/*
-** Exchange the hash part of 't1' and 't2'. (In 'flags', only the dummy
-** bit must be exchanged: The metamethod bits do not change during a
-** resize, so the "real" table can keep their values.)
-*/
-static void exchangehashpart (Table *t1, Table *t2) {
- lu_byte lsizenode = t1->lsizenode;
- Node *node = t1->node;
- int bitdummy1 = t1->flags & BITDUMMY;
- t1->lsizenode = t2->lsizenode;
- t1->node = t2->node;
- t1->flags = cast_byte((t1->flags & NOTBITDUMMY) | (t2->flags & BITDUMMY));
- t2->lsizenode = lsizenode;
- t2->node = node;
- t2->flags = cast_byte((t2->flags & NOTBITDUMMY) | bitdummy1);
-}
-
-
-/*
-** Re-insert into the new hash part of a table the elements from the
-** vanishing slice of the array part.
-*/
-static void reinsertOldSlice (Table *t, unsigned oldasize,
- unsigned newasize) {
- unsigned i;
- for (i = newasize; i < oldasize; i++) { /* traverse vanishing slice */
- lu_byte tag = *getArrTag(t, i);
- if (!tagisempty(tag)) { /* a non-empty entry? */
- TValue key, aux;
- setivalue(&key, l_castU2S(i) + 1); /* make the key */
- farr2val(t, i, tag, &aux); /* copy value into 'aux' */
- insertkey(t, &key, &aux); /* insert entry into the hash part */
- }
- }
-}
-
-
-/*
-** Clear new slice of the array.
-*/
-static void clearNewSlice (Table *t, unsigned oldasize, unsigned newasize) {
- for (; oldasize < newasize; oldasize++)
- *getArrTag(t, oldasize) = LUA_VEMPTY;
-}
-
-
-/*
-** Resize table 't' for the new given sizes. Both allocations (for
-** the hash part and for the array part) can fail, which creates some
-** subtleties. If the first allocation, for the hash part, fails, an
-** error is raised and that is it. Otherwise, it copies the elements from
-** the shrinking part of the array (if it is shrinking) into the new
-** hash. Then it reallocates the array part. If that fails, the table
-** is in its original state; the function frees the new hash part and then
-** raises the allocation error. Otherwise, it sets the new hash part
-** into the table, initializes the new part of the array (if any) with
-** nils and reinserts the elements of the old hash back into the new
-** parts of the table.
-** Note that if the new size for the array part ('newasize') is equal to
-** the old one ('oldasize'), this function will do nothing with that
-** part.
-*/
-void luaH_resize (lua_State *L, Table *t, unsigned newasize,
- unsigned nhsize) {
- Table newt; /* to keep the new hash part */
- unsigned oldasize = t->asize;
- Value *newarray;
- if (newasize > MAXASIZE)
- luaG_runerror(L, "table overflow");
- /* create new hash part with appropriate size into 'newt' */
- newt.flags = 0;
- setnodevector(L, &newt, nhsize);
- if (newasize < oldasize) { /* will array shrink? */
- /* re-insert into the new hash the elements from vanishing slice */
- exchangehashpart(t, &newt); /* pretend table has new hash */
- reinsertOldSlice(t, oldasize, newasize);
- exchangehashpart(t, &newt); /* restore old hash (in case of errors) */
- }
- /* allocate new array */
- newarray = resizearray(L, t, oldasize, newasize);
- if (l_unlikely(newarray == NULL && newasize > 0)) { /* allocation failed? */
- freehash(L, &newt); /* release new hash part */
- luaM_error(L); /* raise error (with array unchanged) */
- }
- /* allocation ok; initialize new part of the array */
- exchangehashpart(t, &newt); /* 't' has the new hash ('newt' has the old) */
- t->array = newarray; /* set new array part */
- t->asize = newasize;
- if (newarray != NULL)
- *lenhint(t) = newasize / 2u; /* set an initial hint */
- clearNewSlice(t, oldasize, newasize);
- /* re-insert elements from old hash part into new parts */
- reinserthash(L, &newt, t); /* 'newt' now has the old hash */
- freehash(L, &newt); /* free old hash part */
-}
-
-
-void luaH_resizearray (lua_State *L, Table *t, unsigned int nasize) {
- unsigned nsize = allocsizenode(t);
- luaH_resize(L, t, nasize, nsize);
-}
-
-
-/*
-** Rehash a table. First, count its keys. If there are array indices
-** outside the array part, compute the new best size for that part.
-** Then, resize the table.
-*/
-static void rehash (lua_State *L, Table *t, const TValue *ek) {
- unsigned asize; /* optimal size for array part */
- Counters ct;
- unsigned i;
- unsigned nsize; /* size for the hash part */
- /* reset counts */
- for (i = 0; i <= MAXABITS; i++) ct.nums[i] = 0;
- ct.na = 0;
- ct.deleted = 0;
- ct.total = 1; /* count extra key */
- if (ttisinteger(ek))
- countint(ivalue(ek), &ct); /* extra key may go to array */
- numusehash(t, &ct); /* count keys in hash part */
- if (ct.na == 0) {
- /* no new keys to enter array part; keep it with the same size */
- asize = t->asize;
- }
- else { /* compute best size for array part */
- numusearray(t, &ct); /* count keys in array part */
- asize = computesizes(&ct); /* compute new size for array part */
- }
- /* all keys not in the array part go to the hash part */
- nsize = ct.total - ct.na;
- if (ct.deleted) { /* table has deleted entries? */
- /* insertion-deletion-insertion: give hash some extra size to
- avoid repeated resizings */
- nsize += nsize >> 2;
- }
- /* resize the table to new computed sizes */
- luaH_resize(L, t, asize, nsize);
-}
-
-/*
-** }=============================================================
-*/
-
-
-Table *luaH_new (lua_State *L) {
- GCObject *o = luaC_newobj(L, LUA_VTABLE, sizeof(Table));
- Table *t = gco2t(o);
- t->metatable = NULL;
- t->flags = maskflags; /* table has no metamethod fields */
- t->array = NULL;
- t->asize = 0;
- setnodevector(L, t, 0);
- return t;
-}
-
-
-lu_mem luaH_size (Table *t) {
- lu_mem sz = cast(lu_mem, sizeof(Table)) + concretesize(t->asize);
- if (!isdummy(t))
- sz += sizehash(t);
- return sz;
-}
-
-
-/*
-** Frees a table.
-*/
-void luaH_free (lua_State *L, Table *t) {
- freehash(L, t);
- resizearray(L, t, t->asize, 0);
- luaM_free(L, t);
-}
-
-
-static Node *getfreepos (Table *t) {
- if (haslastfree(t)) { /* does it have 'lastfree' information? */
- /* look for a spot before 'lastfree', updating 'lastfree' */
- while (getlastfree(t) > t->node) {
- Node *free = --getlastfree(t);
- if (keyisnil(free))
- return free;
- }
- }
- else { /* no 'lastfree' information */
- unsigned i = sizenode(t);
- while (i--) { /* do a linear search */
- Node *free = gnode(t, i);
- if (keyisnil(free))
- return free;
- }
- }
- return NULL; /* could not find a free place */
-}
-
-
-
-/*
-** Inserts a new key into a hash table; first, check whether key's main
-** position is free. If not, check whether colliding node is in its main
-** position or not: if it is not, move colliding node to an empty place
-** and put new key in its main position; otherwise (colliding node is in
-** its main position), new key goes to an empty position. Return 0 if
-** could not insert key (could not find a free space).
-*/
-static int insertkey (Table *t, const TValue *key, TValue *value) {
- Node *mp = mainpositionTV(t, key);
- /* table cannot already contain the key */
- lua_assert(isabstkey(getgeneric(t, key, 0)));
- if (!isempty(gval(mp)) || isdummy(t)) { /* main position is taken? */
- Node *othern;
- Node *f = getfreepos(t); /* get a free place */
- if (f == NULL) /* cannot find a free place? */
- return 0;
- lua_assert(!isdummy(t));
- othern = mainpositionfromnode(t, mp);
- if (othern != mp) { /* is colliding node out of its main position? */
- /* yes; move colliding node into free position */
- while (othern + gnext(othern) != mp) /* find previous */
- othern += gnext(othern);
- gnext(othern) = cast_int(f - othern); /* rechain to point to 'f' */
- *f = *mp; /* copy colliding node into free pos. (mp->next also goes) */
- if (gnext(mp) != 0) {
- gnext(f) += cast_int(mp - f); /* correct 'next' */
- gnext(mp) = 0; /* now 'mp' is free */
- }
- setempty(gval(mp));
- }
- else { /* colliding node is in its own main position */
- /* new node will go into free position */
- if (gnext(mp) != 0)
- gnext(f) = cast_int((mp + gnext(mp)) - f); /* chain new position */
- else lua_assert(gnext(f) == 0);
- gnext(mp) = cast_int(f - mp);
- mp = f;
- }
- }
- setnodekey(mp, key);
- lua_assert(isempty(gval(mp)));
- setobj2t(cast(lua_State *, 0), gval(mp), value);
- return 1;
-}
-
-
-/*
-** Insert a key in a table where there is space for that key, the
-** key is valid, and the value is not nil.
-*/
-static void newcheckedkey (Table *t, const TValue *key, TValue *value) {
- unsigned i = keyinarray(t, key);
- if (i > 0) /* is key in the array part? */
- obj2arr(t, i - 1, value); /* set value in the array */
- else {
- int done = insertkey(t, key, value); /* insert key in the hash part */
- lua_assert(done); /* it cannot fail */
- cast(void, done); /* to avoid warnings */
- }
-}
-
-
-static void luaH_newkey (lua_State *L, Table *t, const TValue *key,
- TValue *value) {
- if (!ttisnil(value)) { /* do not insert nil values */
- int done = insertkey(t, key, value);
- if (!done) { /* could not find a free place? */
- rehash(L, t, key); /* grow table */
- newcheckedkey(t, key, value); /* insert key in grown table */
- }
- luaC_barrierback(L, obj2gco(t), key);
- /* for debugging only: any new key may force an emergency collection */
- condchangemem(L, (void)0, (void)0, 1);
- }
-}
-
-
-static const TValue *getintfromhash (Table *t, lua_Integer key) {
- Node *n = hashint(t, key);
- lua_assert(!ikeyinarray(t, key));
- for (;;) { /* check whether 'key' is somewhere in the chain */
- if (keyisinteger(n) && keyival(n) == key)
- return gval(n); /* that's it */
- else {
- int nx = gnext(n);
- if (nx == 0) break;
- n += nx;
- }
- }
- return &absentkey;
-}
-
-
-static int hashkeyisempty (Table *t, lua_Unsigned key) {
- const TValue *val = getintfromhash(t, l_castU2S(key));
- return isempty(val);
-}
-
-
-static lu_byte finishnodeget (const TValue *val, TValue *res) {
- if (!ttisnil(val)) {
- setobj(((lua_State*)NULL), res, val);
- }
- return ttypetag(val);
-}
-
-
-lu_byte luaH_getint (Table *t, lua_Integer key, TValue *res) {
- unsigned k = ikeyinarray(t, key);
- if (k > 0) {
- lu_byte tag = *getArrTag(t, k - 1);
- if (!tagisempty(tag))
- farr2val(t, k - 1, tag, res);
- return tag;
- }
- else
- return finishnodeget(getintfromhash(t, key), res);
-}
-
-
-/*
-** search function for short strings
-*/
-const TValue *luaH_Hgetshortstr (Table *t, TString *key) {
- Node *n = hashstr(t, key);
- lua_assert(strisshr(key));
- for (;;) { /* check whether 'key' is somewhere in the chain */
- if (keyisshrstr(n) && eqshrstr(keystrval(n), key))
- return gval(n); /* that's it */
- else {
- int nx = gnext(n);
- if (nx == 0)
- return &absentkey; /* not found */
- n += nx;
- }
- }
-}
-
-
-lu_byte luaH_getshortstr (Table *t, TString *key, TValue *res) {
- return finishnodeget(luaH_Hgetshortstr(t, key), res);
-}
-
-
-static const TValue *Hgetlongstr (Table *t, TString *key) {
- TValue ko;
- lua_assert(!strisshr(key));
- setsvalue(cast(lua_State *, NULL), &ko, key);
- return getgeneric(t, &ko, 0); /* for long strings, use generic case */
-}
-
-
-static const TValue *Hgetstr (Table *t, TString *key) {
- if (strisshr(key))
- return luaH_Hgetshortstr(t, key);
- else
- return Hgetlongstr(t, key);
-}
-
-
-lu_byte luaH_getstr (Table *t, TString *key, TValue *res) {
- return finishnodeget(Hgetstr(t, key), res);
-}
-
-
-/*
-** main search function
-*/
-lu_byte luaH_get (Table *t, const TValue *key, TValue *res) {
- const TValue *slot;
- switch (ttypetag(key)) {
- case LUA_VSHRSTR:
- slot = luaH_Hgetshortstr(t, tsvalue(key));
- break;
- case LUA_VNUMINT:
- return luaH_getint(t, ivalue(key), res);
- case LUA_VNIL:
- slot = &absentkey;
- break;
- case LUA_VNUMFLT: {
- lua_Integer k;
- if (luaV_flttointeger(fltvalue(key), &k, F2Ieq)) /* integral index? */
- return luaH_getint(t, k, res); /* use specialized version */
- /* else... */
- } /* FALLTHROUGH */
- default:
- slot = getgeneric(t, key, 0);
- break;
- }
- return finishnodeget(slot, res);
-}
-
-
-/*
-** When a 'pset' cannot be completed, this function returns an encoding
-** of its result, to be used by 'luaH_finishset'.
-*/
-static int retpsetcode (Table *t, const TValue *slot) {
- if (isabstkey(slot))
- return HNOTFOUND; /* no slot with that key */
- else /* return node encoded */
- return cast_int((cast(Node*, slot) - t->node)) + HFIRSTNODE;
-}
-
-
-static int finishnodeset (Table *t, const TValue *slot, TValue *val) {
- if (!ttisnil(slot)) {
- setobj(((lua_State*)NULL), cast(TValue*, slot), val);
- return HOK; /* success */
- }
- else
- return retpsetcode(t, slot);
-}
-
-
-static int rawfinishnodeset (const TValue *slot, TValue *val) {
- if (isabstkey(slot))
- return 0; /* no slot with that key */
- else {
- setobj(((lua_State*)NULL), cast(TValue*, slot), val);
- return 1; /* success */
- }
-}
-
-
-int luaH_psetint (Table *t, lua_Integer key, TValue *val) {
- lua_assert(!ikeyinarray(t, key));
- return finishnodeset(t, getintfromhash(t, key), val);
-}
-
-
-static int psetint (Table *t, lua_Integer key, TValue *val) {
- int hres;
- luaH_fastseti(t, key, val, hres);
- return hres;
-}
-
-
-/*
-** This function could be just this:
-** return finishnodeset(t, luaH_Hgetshortstr(t, key), val);
-** However, it optimizes the common case created by constructors (e.g.,
-** {x=1, y=2}), which creates a key in a table that has no metatable,
-** it is not old/black, and it already has space for the key.
-*/
-
-int luaH_psetshortstr (Table *t, TString *key, TValue *val) {
- const TValue *slot = luaH_Hgetshortstr(t, key);
- if (!ttisnil(slot)) { /* key already has a value? (all too common) */
- setobj(((lua_State*)NULL), cast(TValue*, slot), val); /* update it */
- return HOK; /* done */
- }
- else if (checknoTM(t->metatable, TM_NEWINDEX)) { /* no metamethod? */
- if (ttisnil(val)) /* new value is nil? */
- return HOK; /* done (value is already nil/absent) */
- if (isabstkey(slot) && /* key is absent? */
- !(isblack(t) && iswhite(key))) { /* and don't need barrier? */
- TValue tk; /* key as a TValue */
- setsvalue(cast(lua_State *, NULL), &tk, key);
- if (insertkey(t, &tk, val)) { /* insert key, if there is space */
- invalidateTMcache(t);
- return HOK;
- }
- }
- }
- /* Else, either table has new-index metamethod, or it needs barrier,
- or it needs to rehash for the new key. In any of these cases, the
- operation cannot be completed here. Return a code for the caller. */
- return retpsetcode(t, slot);
-}
-
-
-int luaH_psetstr (Table *t, TString *key, TValue *val) {
- if (strisshr(key))
- return luaH_psetshortstr(t, key, val);
- else
- return finishnodeset(t, Hgetlongstr(t, key), val);
-}
-
-
-int luaH_pset (Table *t, const TValue *key, TValue *val) {
- switch (ttypetag(key)) {
- case LUA_VSHRSTR: return luaH_psetshortstr(t, tsvalue(key), val);
- case LUA_VNUMINT: return psetint(t, ivalue(key), val);
- case LUA_VNIL: return HNOTFOUND;
- case LUA_VNUMFLT: {
- lua_Integer k;
- if (luaV_flttointeger(fltvalue(key), &k, F2Ieq)) /* integral index? */
- return psetint(t, k, val); /* use specialized version */
- /* else... */
- } /* FALLTHROUGH */
- default:
- return finishnodeset(t, getgeneric(t, key, 0), val);
- }
-}
-
-/*
-** Finish a raw "set table" operation, where 'hres' encodes where the
-** value should have been (the result of a previous 'pset' operation).
-** Beware: when using this function the caller probably need to check a
-** GC barrier and invalidate the TM cache.
-*/
-void luaH_finishset (lua_State *L, Table *t, const TValue *key,
- TValue *value, int hres) {
- lua_assert(hres != HOK);
- if (hres == HNOTFOUND) {
- TValue aux;
- const TValue *actk = key; /* actual key to insert */
- if (l_unlikely(ttisnil(key)))
- luaG_runerror(L, "table index is nil");
- else if (ttisfloat(key)) {
- lua_Number f = fltvalue(key);
- lua_Integer k;
- if (luaV_flttointeger(f, &k, F2Ieq)) { /* is key equal to an integer? */
- setivalue(&aux, k);
- actk = &aux; /* use the integer as the key */
- }
- else if (l_unlikely(luai_numisnan(f)))
- luaG_runerror(L, "table index is NaN");
- }
- else if (isextstr(key)) { /* external string? */
- /* If string is short, must internalize it to be used as table key */
- TString *ts = luaS_normstr(L, tsvalue(key));
- setsvalue2s(L, L->top.p++, ts); /* anchor 'ts' (EXTRA_STACK) */
- luaH_newkey(L, t, s2v(L->top.p - 1), value);
- L->top.p--;
- return;
- }
- luaH_newkey(L, t, actk, value);
- }
- else if (hres > 0) { /* regular Node? */
- setobj2t(L, gval(gnode(t, hres - HFIRSTNODE)), value);
- }
- else { /* array entry */
- hres = ~hres; /* real index */
- obj2arr(t, cast_uint(hres), value);
- }
-}
-
-
-/*
-** beware: when using this function you probably need to check a GC
-** barrier and invalidate the TM cache.
-*/
-void luaH_set (lua_State *L, Table *t, const TValue *key, TValue *value) {
- int hres = luaH_pset(t, key, value);
- if (hres != HOK)
- luaH_finishset(L, t, key, value, hres);
-}
-
-
-/*
-** Ditto for a GC barrier. (No need to invalidate the TM cache, as
-** integers cannot be keys to metamethods.)
-*/
-void luaH_setint (lua_State *L, Table *t, lua_Integer key, TValue *value) {
- unsigned ik = ikeyinarray(t, key);
- if (ik > 0)
- obj2arr(t, ik - 1, value);
- else {
- int ok = rawfinishnodeset(getintfromhash(t, key), value);
- if (!ok) {
- TValue k;
- setivalue(&k, key);
- luaH_newkey(L, t, &k, value);
- }
- }
-}
-
-
-/*
-** Try to find a boundary in the hash part of table 't'. From the
-** caller, we know that 'asize + 1' is present. We want to find a larger
-** key that is absent from the table, so that we can do a binary search
-** between the two keys to find a boundary. We keep doubling 'j' until
-** we get an absent index. If the doubling would overflow, we try
-** LUA_MAXINTEGER. If it is absent, we are ready for the binary search.
-** ('j', being max integer, is larger or equal to 'i', but it cannot be
-** equal because it is absent while 'i' is present.) Otherwise, 'j' is a
-** boundary. ('j + 1' cannot be a present integer key because it is not
-** a valid integer in Lua.)
-** About 'rnd': If we used a fixed algorithm, a bad actor could fill
-** a table with only the keys that would be probed, in such a way that
-** a small table could result in a huge length. To avoid that, we use
-** the state's seed as a source of randomness. For the first probe,
-** we "randomly double" 'i' by adding to it a random number roughly its
-** width.
-*/
-static lua_Unsigned hash_search (lua_State *L, Table *t, unsigned asize) {
- lua_Unsigned i = asize + 1; /* caller ensures t[i] is present */
- unsigned rnd = G(L)->seed;
- int n = (asize > 0) ? luaO_ceillog2(asize) : 0; /* width of 'asize' */
- unsigned mask = (1u << n) - 1; /* 11...111 with the width of 'asize' */
- unsigned incr = (rnd & mask) + 1; /* first increment (at least 1) */
- lua_Unsigned j = (incr <= l_castS2U(LUA_MAXINTEGER) - i) ? i + incr : i + 1;
- rnd >>= n; /* used 'n' bits from 'rnd' */
- while (!hashkeyisempty(t, j)) { /* repeat until an absent t[j] */
- i = j; /* 'i' is a present index */
- if (j <= l_castS2U(LUA_MAXINTEGER)/2 - 1) {
- j = j*2 + (rnd & 1); /* try again with 2j or 2j+1 */
- rnd >>= 1;
- }
- else {
- j = LUA_MAXINTEGER;
- if (hashkeyisempty(t, j)) /* t[j] not present? */
- break; /* 'j' now is an absent index */
- else /* weird case */
- return j; /* well, max integer is a boundary... */
- }
- }
- /* i < j && t[i] present && t[j] absent */
- while (j - i > 1u) { /* do a binary search between them */
- lua_Unsigned m = (i + j) / 2;
- if (hashkeyisempty(t, m)) j = m;
- else i = m;
- }
- return i;
-}
-
-
-static unsigned int binsearch (Table *array, unsigned int i, unsigned int j) {
- lua_assert(i <= j);
- while (j - i > 1u) { /* binary search */
- unsigned int m = (i + j) / 2;
- if (arraykeyisempty(array, m)) j = m;
- else i = m;
- }
- return i;
-}
-
-
-/* return a border, saving it as a hint for next call */
-static lua_Unsigned newhint (Table *t, unsigned hint) {
- lua_assert(hint <= t->asize);
- *lenhint(t) = hint;
- return hint;
-}
-
-
-/*
-** Try to find a border in table 't'. (A 'border' is an integer index
-** such that t[i] is present and t[i+1] is absent, or 0 if t[1] is absent,
-** or 'maxinteger' if t[maxinteger] is present.)
-** If there is an array part, try to find a border there. First try
-** to find it in the vicinity of the previous result (hint), to handle
-** cases like 't[#t + 1] = val' or 't[#t] = nil', that move the border
-** by one entry. Otherwise, do a binary search to find the border.
-** If there is no array part, or its last element is non empty, the
-** border may be in the hash part.
-*/
-lua_Unsigned luaH_getn (lua_State *L, Table *t) {
- unsigned asize = t->asize;
- if (asize > 0) { /* is there an array part? */
- const unsigned maxvicinity = 4;
- unsigned limit = *lenhint(t); /* start with the hint */
- if (limit == 0)
- limit = 1; /* make limit a valid index in the array */
- if (arraykeyisempty(t, limit)) { /* t[limit] empty? */
- /* there must be a border before 'limit' */
- unsigned i;
- /* look for a border in the vicinity of the hint */
- for (i = 0; i < maxvicinity && limit > 1; i++) {
- limit--;
- if (!arraykeyisempty(t, limit))
- return newhint(t, limit); /* 'limit' is a border */
- }
- /* t[limit] still empty; search for a border in [0, limit) */
- return newhint(t, binsearch(t, 0, limit));
- }
- else { /* 'limit' is present in table; look for a border after it */
- unsigned i;
- /* look for a border in the vicinity of the hint */
- for (i = 0; i < maxvicinity && limit < asize; i++) {
- limit++;
- if (arraykeyisempty(t, limit))
- return newhint(t, limit - 1); /* 'limit - 1' is a border */
- }
- if (arraykeyisempty(t, asize)) { /* last element empty? */
- /* t[limit] not empty; search for a border in [limit, asize) */
- return newhint(t, binsearch(t, limit, asize));
- }
- }
- /* last element non empty; set a hint to speed up finding that again */
- /* (keys in the hash part cannot be hints) */
- *lenhint(t) = asize;
- }
- /* no array part or t[asize] is not empty; check the hash part */
- lua_assert(asize == 0 || !arraykeyisempty(t, asize));
- if (isdummy(t) || hashkeyisempty(t, asize + 1))
- return asize; /* 'asize + 1' is empty */
- else /* 'asize + 1' is also non empty */
- return hash_search(L, t, asize);
-}
-
-
-
-#if defined(LUA_DEBUG)
-
-/* export this function for the test library */
-
-Node *luaH_mainposition (const Table *t, const TValue *key) {
- return mainpositionTV(t, key);
-}
-
-#endif
diff --git a/ltable.h b/ltable.h
deleted file mode 100644
index f3b7bc7e7e..0000000000
--- a/ltable.h
+++ /dev/null
@@ -1,184 +0,0 @@
-/*
-** $Id: ltable.h $
-** Lua tables (hash)
-** See Copyright Notice in lua.h
-*/
-
-#ifndef ltable_h
-#define ltable_h
-
-#include "lobject.h"
-
-
-#define gnode(t,i) (&(t)->node[i])
-#define gval(n) (&(n)->i_val)
-#define gnext(n) ((n)->u.next)
-
-
-/*
-** Clear all bits of fast-access metamethods, which means that the table
-** may have any of these metamethods. (First access that fails after the
-** clearing will set the bit again.)
-*/
-#define invalidateTMcache(t) ((t)->flags &= cast_byte(~maskflags))
-
-
-/*
-** Bit BITDUMMY set in 'flags' means the table is using the dummy node
-** for its hash part.
-*/
-
-#define BITDUMMY (1 << 6)
-#define NOTBITDUMMY cast_byte(~BITDUMMY)
-#define isdummy(t) ((t)->flags & BITDUMMY)
-
-#define setnodummy(t) ((t)->flags &= NOTBITDUMMY)
-#define setdummy(t) ((t)->flags |= BITDUMMY)
-
-
-
-/* allocated size for hash nodes */
-#define allocsizenode(t) (isdummy(t) ? 0 : sizenode(t))
-
-
-/* returns the Node, given the value of a table entry */
-#define nodefromval(v) cast(Node *, (v))
-
-
-
-#define luaH_fastgeti(t,k,res,tag) \
- { Table *h = t; lua_Unsigned u = l_castS2U(k) - 1u; \
- if ((u < h->asize)) { \
- tag = *getArrTag(h, u); \
- if (!tagisempty(tag)) { farr2val(h, u, tag, res); }} \
- else { tag = luaH_getint(h, (k), res); }}
-
-
-#define luaH_fastseti(t,k,val,hres) \
- { Table *h = t; lua_Unsigned u = l_castS2U(k) - 1u; \
- if ((u < h->asize)) { \
- lu_byte *tag = getArrTag(h, u); \
- if (checknoTM(h->metatable, TM_NEWINDEX) || !tagisempty(*tag)) \
- { fval2arr(h, u, tag, val); hres = HOK; } \
- else hres = ~cast_int(u); } \
- else { hres = luaH_psetint(h, k, val); }}
-
-
-/* results from pset */
-#define HOK 0
-#define HNOTFOUND 1
-#define HNOTATABLE 2
-#define HFIRSTNODE 3
-
-/*
-** 'luaH_get*' operations set 'res', unless the value is absent, and
-** return the tag of the result.
-** The 'luaH_pset*' (pre-set) operations set the given value and return
-** HOK, unless the original value is absent. In that case, if the key
-** is really absent, they return HNOTFOUND. Otherwise, if there is a
-** slot with that key but with no value, 'luaH_pset*' return an encoding
-** of where the key is (usually called 'hres'). (pset cannot set that
-** value because there might be a metamethod.) If the slot is in the
-** hash part, the encoding is (HFIRSTNODE + hash index); if the slot is
-** in the array part, the encoding is (~array index), a negative value.
-** The value HNOTATABLE is used by the fast macros to signal that the
-** value being indexed is not a table.
-** (The size for the array part is limited by the maximum power of two
-** that fits in an unsigned integer; that is INT_MAX+1. So, the C-index
-** ranges from 0, which encodes to -1, to INT_MAX, which encodes to
-** INT_MIN. The size of the hash part is limited by the maximum power of
-** two that fits in a signed integer; that is (INT_MAX+1)/2. So, it is
-** safe to add HFIRSTNODE to any index there.)
-*/
-
-
-/*
-** The array part of a table is represented by an inverted array of
-** values followed by an array of tags, to avoid wasting space with
-** padding. In between them there is an unsigned int, explained later.
-** The 'array' pointer points between the two arrays, so that values are
-** indexed with negative indices and tags with non-negative indices.
-
- Values Tags
- --------------------------------------------------------
- ... | Value 1 | Value 0 |unsigned|0|1|...
- --------------------------------------------------------
- ^ t->array
-
-** All accesses to 't->array' should be through the macros 'getArrTag'
-** and 'getArrVal'.
-*/
-
-/* Computes the address of the tag for the abstract C-index 'k' */
-#define getArrTag(t,k) (cast(lu_byte*, (t)->array) + sizeof(unsigned) + (k))
-
-/* Computes the address of the value for the abstract C-index 'k' */
-#define getArrVal(t,k) ((t)->array - 1 - (k))
-
-
-/*
-** The unsigned between the two arrays is used as a hint for #t;
-** see luaH_getn. It is stored there to avoid wasting space in
-** the structure Table for tables with no array part.
-*/
-#define lenhint(t) cast(unsigned*, (t)->array)
-
-
-/*
-** Move TValues to/from arrays, using C indices
-*/
-#define arr2obj(h,k,val) \
- ((val)->tt_ = *getArrTag(h,(k)), (val)->value_ = *getArrVal(h,(k)))
-
-#define obj2arr(h,k,val) \
- (*getArrTag(h,(k)) = (val)->tt_, *getArrVal(h,(k)) = (val)->value_)
-
-
-/*
-** Often, we need to check the tag of a value before moving it. The
-** following macros also move TValues to/from arrays, but receive the
-** precomputed tag value or address as an extra argument.
-*/
-#define farr2val(h,k,tag,res) \
- ((res)->tt_ = tag, (res)->value_ = *getArrVal(h,(k)))
-
-#define fval2arr(h,k,tag,val) \
- (*tag = (val)->tt_, *getArrVal(h,(k)) = (val)->value_)
-
-
-LUAI_FUNC lu_byte luaH_get (Table *t, const TValue *key, TValue *res);
-LUAI_FUNC lu_byte luaH_getshortstr (Table *t, TString *key, TValue *res);
-LUAI_FUNC lu_byte luaH_getstr (Table *t, TString *key, TValue *res);
-LUAI_FUNC lu_byte luaH_getint (Table *t, lua_Integer key, TValue *res);
-
-/* Special get for metamethods */
-LUAI_FUNC const TValue *luaH_Hgetshortstr (Table *t, TString *key);
-
-LUAI_FUNC int luaH_psetint (Table *t, lua_Integer key, TValue *val);
-LUAI_FUNC int luaH_psetshortstr (Table *t, TString *key, TValue *val);
-LUAI_FUNC int luaH_psetstr (Table *t, TString *key, TValue *val);
-LUAI_FUNC int luaH_pset (Table *t, const TValue *key, TValue *val);
-
-LUAI_FUNC void luaH_setint (lua_State *L, Table *t, lua_Integer key,
- TValue *value);
-LUAI_FUNC void luaH_set (lua_State *L, Table *t, const TValue *key,
- TValue *value);
-
-LUAI_FUNC void luaH_finishset (lua_State *L, Table *t, const TValue *key,
- TValue *value, int hres);
-LUAI_FUNC Table *luaH_new (lua_State *L);
-LUAI_FUNC void luaH_resize (lua_State *L, Table *t, unsigned nasize,
- unsigned nhsize);
-LUAI_FUNC void luaH_resizearray (lua_State *L, Table *t, unsigned nasize);
-LUAI_FUNC lu_mem luaH_size (Table *t);
-LUAI_FUNC void luaH_free (lua_State *L, Table *t);
-LUAI_FUNC int luaH_next (lua_State *L, Table *t, StkId key);
-LUAI_FUNC lua_Unsigned luaH_getn (lua_State *L, Table *t);
-
-
-#if defined(LUA_DEBUG)
-LUAI_FUNC Node *luaH_mainposition (const Table *t, const TValue *key);
-#endif
-
-
-#endif
diff --git a/ltablib.c b/ltablib.c
deleted file mode 100644
index 15c3c09f04..0000000000
--- a/ltablib.c
+++ /dev/null
@@ -1,429 +0,0 @@
-/*
-** $Id: ltablib.c $
-** Library for Table Manipulation
-** See Copyright Notice in lua.h
-*/
-
-#define ltablib_c
-#define LUA_LIB
-
-#include "lprefix.h"
-
-
-#include
-#include
-#include
-
-#include "lua.h"
-
-#include "lauxlib.h"
-#include "lualib.h"
-#include "llimits.h"
-
-
-/*
-** Operations that an object must define to mimic a table
-** (some functions only need some of them)
-*/
-#define TAB_R 1 /* read */
-#define TAB_W 2 /* write */
-#define TAB_L 4 /* length */
-#define TAB_RW (TAB_R | TAB_W) /* read/write */
-
-
-#define aux_getn(L,n,w) (checktab(L, n, (w) | TAB_L), luaL_len(L, n))
-
-
-static int checkfield (lua_State *L, const char *key, int n) {
- lua_pushstring(L, key);
- return (lua_rawget(L, -n) != LUA_TNIL);
-}
-
-
-/*
-** Check that 'arg' either is a table or can behave like one (that is,
-** has a metatable with the required metamethods).
-*/
-static void checktab (lua_State *L, int arg, int what) {
- int tp = lua_type(L, arg);
- if (tp != LUA_TTABLE) { /* is it not a table? */
- int n = 1; /* number of elements to pop */
- if (lua_getmetatable(L, arg) && /* must have metatable */
- (!(what & TAB_R) || checkfield(L, "__index", ++n)) &&
- (!(what & TAB_W) || checkfield(L, "__newindex", ++n)) &&
- (!(what & TAB_L) || /* strings don't need '__len' to have a length */
- tp == LUA_TSTRING || checkfield(L, "__len", ++n))) {
- lua_pop(L, n); /* pop metatable and tested metamethods */
- }
- else
- luaL_checktype(L, arg, LUA_TTABLE); /* force an error */
- }
-}
-
-
-static int tcreate (lua_State *L) {
- lua_Unsigned sizeseq = (lua_Unsigned)luaL_checkinteger(L, 1);
- lua_Unsigned sizerest = (lua_Unsigned)luaL_optinteger(L, 2, 0);
- luaL_argcheck(L, sizeseq <= cast_uint(INT_MAX), 1, "out of range");
- luaL_argcheck(L, sizerest <= cast_uint(INT_MAX), 2, "out of range");
- lua_createtable(L, cast_int(sizeseq), cast_int(sizerest));
- return 1;
-}
-
-
-static int tinsert (lua_State *L) {
- lua_Integer pos; /* where to insert new element */
- lua_Integer e = aux_getn(L, 1, TAB_RW);
- e = luaL_intop(+, e, 1); /* first empty element */
- switch (lua_gettop(L)) {
- case 2: { /* called with only 2 arguments */
- pos = e; /* insert new element at the end */
- break;
- }
- case 3: {
- lua_Integer i;
- pos = luaL_checkinteger(L, 2); /* 2nd argument is the position */
- /* check whether 'pos' is in [1, e] */
- luaL_argcheck(L, (lua_Unsigned)pos - 1u < (lua_Unsigned)e, 2,
- "position out of bounds");
- for (i = e; i > pos; i--) { /* move up elements */
- lua_geti(L, 1, i - 1);
- lua_seti(L, 1, i); /* t[i] = t[i - 1] */
- }
- break;
- }
- default: {
- return luaL_error(L, "wrong number of arguments to 'insert'");
- }
- }
- lua_seti(L, 1, pos); /* t[pos] = v */
- return 0;
-}
-
-
-static int tremove (lua_State *L) {
- lua_Integer size = aux_getn(L, 1, TAB_RW);
- lua_Integer pos = luaL_optinteger(L, 2, size);
- if (pos != size) /* validate 'pos' if given */
- /* check whether 'pos' is in [1, size + 1] */
- luaL_argcheck(L, (lua_Unsigned)pos - 1u <= (lua_Unsigned)size, 2,
- "position out of bounds");
- lua_geti(L, 1, pos); /* result = t[pos] */
- for ( ; pos < size; pos++) {
- lua_geti(L, 1, pos + 1);
- lua_seti(L, 1, pos); /* t[pos] = t[pos + 1] */
- }
- lua_pushnil(L);
- lua_seti(L, 1, pos); /* remove entry t[pos] */
- return 1;
-}
-
-
-/*
-** Copy elements (1[f], ..., 1[e]) into (tt[t], tt[t+1], ...). Whenever
-** possible, copy in increasing order, which is better for rehashing.
-** "possible" means destination after original range, or smaller
-** than origin, or copying to another table.
-*/
-static int tmove (lua_State *L) {
- lua_Integer f = luaL_checkinteger(L, 2);
- lua_Integer e = luaL_checkinteger(L, 3);
- lua_Integer t = luaL_checkinteger(L, 4);
- int tt = !lua_isnoneornil(L, 5) ? 5 : 1; /* destination table */
- checktab(L, 1, TAB_R);
- checktab(L, tt, TAB_W);
- if (e >= f) { /* otherwise, nothing to move */
- lua_Integer n, i;
- luaL_argcheck(L, f > 0 || e < LUA_MAXINTEGER + f, 3,
- "too many elements to move");
- n = e - f + 1; /* number of elements to move */
- luaL_argcheck(L, t <= LUA_MAXINTEGER - n + 1, 4,
- "destination wrap around");
- if (t > e || t <= f || (tt != 1 && !lua_compare(L, 1, tt, LUA_OPEQ))) {
- for (i = 0; i < n; i++) {
- lua_geti(L, 1, f + i);
- lua_seti(L, tt, t + i);
- }
- }
- else {
- for (i = n - 1; i >= 0; i--) {
- lua_geti(L, 1, f + i);
- lua_seti(L, tt, t + i);
- }
- }
- }
- lua_pushvalue(L, tt); /* return destination table */
- return 1;
-}
-
-
-static void addfield (lua_State *L, luaL_Buffer *b, lua_Integer i) {
- lua_geti(L, 1, i);
- if (l_unlikely(!lua_isstring(L, -1)))
- luaL_error(L, "invalid value (%s) at index %I in table for 'concat'",
- luaL_typename(L, -1), (LUAI_UACINT)i);
- luaL_addvalue(b);
-}
-
-
-static int tconcat (lua_State *L) {
- luaL_Buffer b;
- lua_Integer last = aux_getn(L, 1, TAB_R);
- size_t lsep;
- const char *sep = luaL_optlstring(L, 2, "", &lsep);
- lua_Integer i = luaL_optinteger(L, 3, 1);
- last = luaL_optinteger(L, 4, last);
- luaL_buffinit(L, &b);
- for (; i < last; i++) {
- addfield(L, &b, i);
- luaL_addlstring(&b, sep, lsep);
- }
- if (i == last) /* add last value (if interval was not empty) */
- addfield(L, &b, i);
- luaL_pushresult(&b);
- return 1;
-}
-
-
-/*
-** {======================================================
-** Pack/unpack
-** =======================================================
-*/
-
-static int tpack (lua_State *L) {
- int i;
- int n = lua_gettop(L); /* number of elements to pack */
- lua_createtable(L, n, 1); /* create result table */
- lua_insert(L, 1); /* put it at index 1 */
- for (i = n; i >= 1; i--) /* assign elements */
- lua_seti(L, 1, i);
- lua_pushinteger(L, n);
- lua_setfield(L, 1, "n"); /* t.n = number of elements */
- return 1; /* return table */
-}
-
-
-static int tunpack (lua_State *L) {
- lua_Unsigned n;
- lua_Integer len = aux_getn(L, 1, TAB_R);
- lua_Integer i = luaL_optinteger(L, 2, 1);
- lua_Integer e = luaL_opt(L, luaL_checkinteger, 3, len);
- if (i > e) return 0; /* empty range */
- n = l_castS2U(e) - l_castS2U(i); /* number of elements minus 1 */
- if (l_unlikely(n >= (unsigned int)INT_MAX ||
- !lua_checkstack(L, (int)(++n))))
- return luaL_error(L, "too many results to unpack");
- for (; i < e; i++) { /* push arg[i..e - 1] (to avoid overflows) */
- lua_geti(L, 1, i);
- }
- lua_geti(L, 1, e); /* push last element */
- return (int)n;
-}
-
-/* }====================================================== */
-
-
-
-/*
-** {======================================================
-** Quicksort
-** (based on 'Algorithms in MODULA-3', Robert Sedgewick;
-** Addison-Wesley, 1993.)
-** =======================================================
-*/
-
-
-/*
-** Type for array indices. These indices are always limited by INT_MAX,
-** so it is safe to cast them to lua_Integer even for Lua 32 bits.
-*/
-typedef unsigned int IdxT;
-
-
-/* Versions of lua_seti/lua_geti specialized for IdxT */
-#define geti(L,idt,idx) lua_geti(L, idt, l_castU2S(idx))
-#define seti(L,idt,idx) lua_seti(L, idt, l_castU2S(idx))
-
-
-/*
-** Produce a "random" 'unsigned int' to randomize pivot choice. This
-** macro is used only when 'sort' detects a big imbalance in the result
-** of a partition. (If you don't want/need this "randomness", ~0 is a
-** good choice.)
-*/
-#if !defined(l_randomizePivot)
-#define l_randomizePivot(L) luaL_makeseed(L)
-#endif /* } */
-
-
-/* arrays larger than 'RANLIMIT' may use randomized pivots */
-#define RANLIMIT 100u
-
-
-static void set2 (lua_State *L, IdxT i, IdxT j) {
- seti(L, 1, i);
- seti(L, 1, j);
-}
-
-
-/*
-** Return true iff value at stack index 'a' is less than the value at
-** index 'b' (according to the order of the sort).
-*/
-static int sort_comp (lua_State *L, int a, int b) {
- if (lua_isnil(L, 2)) /* no function? */
- return lua_compare(L, a, b, LUA_OPLT); /* a < b */
- else { /* function */
- int res;
- lua_pushvalue(L, 2); /* push function */
- lua_pushvalue(L, a-1); /* -1 to compensate function */
- lua_pushvalue(L, b-2); /* -2 to compensate function and 'a' */
- lua_call(L, 2, 1); /* call function */
- res = lua_toboolean(L, -1); /* get result */
- lua_pop(L, 1); /* pop result */
- return res;
- }
-}
-
-
-/*
-** Does the partition: Pivot P is at the top of the stack.
-** precondition: a[lo] <= P == a[up-1] <= a[up],
-** so it only needs to do the partition from lo + 1 to up - 2.
-** Pos-condition: a[lo .. i - 1] <= a[i] == P <= a[i + 1 .. up]
-** returns 'i'.
-*/
-static IdxT partition (lua_State *L, IdxT lo, IdxT up) {
- IdxT i = lo; /* will be incremented before first use */
- IdxT j = up - 1; /* will be decremented before first use */
- /* loop invariant: a[lo .. i] <= P <= a[j .. up] */
- for (;;) {
- /* next loop: repeat ++i while a[i] < P */
- while ((void)geti(L, 1, ++i), sort_comp(L, -1, -2)) {
- if (l_unlikely(i == up - 1)) /* a[up - 1] < P == a[up - 1] */
- luaL_error(L, "invalid order function for sorting");
- lua_pop(L, 1); /* remove a[i] */
- }
- /* after the loop, a[i] >= P and a[lo .. i - 1] < P (a) */
- /* next loop: repeat --j while P < a[j] */
- while ((void)geti(L, 1, --j), sort_comp(L, -3, -1)) {
- if (l_unlikely(j < i)) /* j <= i - 1 and a[j] > P, contradicts (a) */
- luaL_error(L, "invalid order function for sorting");
- lua_pop(L, 1); /* remove a[j] */
- }
- /* after the loop, a[j] <= P and a[j + 1 .. up] >= P */
- if (j < i) { /* no elements out of place? */
- /* a[lo .. i - 1] <= P <= a[j + 1 .. i .. up] */
- lua_pop(L, 1); /* pop a[j] */
- /* swap pivot (a[up - 1]) with a[i] to satisfy pos-condition */
- set2(L, up - 1, i);
- return i;
- }
- /* otherwise, swap a[i] - a[j] to restore invariant and repeat */
- set2(L, i, j);
- }
-}
-
-
-/*
-** Choose an element in the middle (2nd-3th quarters) of [lo,up]
-** "randomized" by 'rnd'
-*/
-static IdxT choosePivot (IdxT lo, IdxT up, unsigned int rnd) {
- IdxT r4 = (up - lo) / 4; /* range/4 */
- IdxT p = (rnd ^ lo ^ up) % (r4 * 2) + (lo + r4);
- lua_assert(lo + r4 <= p && p <= up - r4);
- return p;
-}
-
-
-/*
-** Quicksort algorithm (recursive function)
-*/
-static void auxsort (lua_State *L, IdxT lo, IdxT up, unsigned rnd) {
- while (lo < up) { /* loop for tail recursion */
- IdxT p; /* Pivot index */
- IdxT n; /* to be used later */
- /* sort elements 'lo', 'p', and 'up' */
- geti(L, 1, lo);
- geti(L, 1, up);
- if (sort_comp(L, -1, -2)) /* a[up] < a[lo]? */
- set2(L, lo, up); /* swap a[lo] - a[up] */
- else
- lua_pop(L, 2); /* remove both values */
- if (up - lo == 1) /* only 2 elements? */
- return; /* already sorted */
- if (up - lo < RANLIMIT || rnd == 0) /* small interval or no randomize? */
- p = (lo + up)/2; /* middle element is a good pivot */
- else /* for larger intervals, it is worth a random pivot */
- p = choosePivot(lo, up, rnd);
- geti(L, 1, p);
- geti(L, 1, lo);
- if (sort_comp(L, -2, -1)) /* a[p] < a[lo]? */
- set2(L, p, lo); /* swap a[p] - a[lo] */
- else {
- lua_pop(L, 1); /* remove a[lo] */
- geti(L, 1, up);
- if (sort_comp(L, -1, -2)) /* a[up] < a[p]? */
- set2(L, p, up); /* swap a[up] - a[p] */
- else
- lua_pop(L, 2);
- }
- if (up - lo == 2) /* only 3 elements? */
- return; /* already sorted */
- geti(L, 1, p); /* get middle element (Pivot) */
- lua_pushvalue(L, -1); /* push Pivot */
- geti(L, 1, up - 1); /* push a[up - 1] */
- set2(L, p, up - 1); /* swap Pivot (a[p]) with a[up - 1] */
- p = partition(L, lo, up);
- /* a[lo .. p - 1] <= a[p] == P <= a[p + 1 .. up] */
- if (p - lo < up - p) { /* lower interval is smaller? */
- auxsort(L, lo, p - 1, rnd); /* call recursively for lower interval */
- n = p - lo; /* size of smaller interval */
- lo = p + 1; /* tail call for [p + 1 .. up] (upper interval) */
- }
- else {
- auxsort(L, p + 1, up, rnd); /* call recursively for upper interval */
- n = up - p; /* size of smaller interval */
- up = p - 1; /* tail call for [lo .. p - 1] (lower interval) */
- }
- if ((up - lo) / 128 > n) /* partition too imbalanced? */
- rnd = l_randomizePivot(L); /* try a new randomization */
- } /* tail call auxsort(L, lo, up, rnd) */
-}
-
-
-static int sort (lua_State *L) {
- lua_Integer n = aux_getn(L, 1, TAB_RW);
- if (n > 1) { /* non-trivial interval? */
- luaL_argcheck(L, n < INT_MAX, 1, "array too big");
- if (!lua_isnoneornil(L, 2)) /* is there a 2nd argument? */
- luaL_checktype(L, 2, LUA_TFUNCTION); /* must be a function */
- lua_settop(L, 2); /* make sure there are two arguments */
- auxsort(L, 1, (IdxT)n, 0);
- }
- return 0;
-}
-
-/* }====================================================== */
-
-
-static const luaL_Reg tab_funcs[] = {
- {"concat", tconcat},
- {"create", tcreate},
- {"insert", tinsert},
- {"pack", tpack},
- {"unpack", tunpack},
- {"remove", tremove},
- {"move", tmove},
- {"sort", sort},
- {NULL, NULL}
-};
-
-
-LUAMOD_API int luaopen_table (lua_State *L) {
- luaL_newlib(L, tab_funcs);
- return 1;
-}
-
diff --git a/ltests.c b/ltests.c
deleted file mode 100644
index ce2b20ca5e..0000000000
--- a/ltests.c
+++ /dev/null
@@ -1,2247 +0,0 @@
-/*
-** $Id: ltests.c $
-** Internal Module for Debugging of the Lua Implementation
-** See Copyright Notice in lua.h
-*/
-
-#define ltests_c
-#define LUA_CORE
-
-#include "lprefix.h"
-
-
-#include
-#include
-#include
-#include
-#include
-
-#include "lua.h"
-
-#include "lapi.h"
-#include "lauxlib.h"
-#include "lcode.h"
-#include "lctype.h"
-#include "ldebug.h"
-#include "ldo.h"
-#include "lfunc.h"
-#include "lmem.h"
-#include "lopcodes.h"
-#include "lopnames.h"
-#include "lstate.h"
-#include "lstring.h"
-#include "ltable.h"
-#include "lualib.h"
-
-
-
-/*
-** The whole module only makes sense with LUA_DEBUG on
-*/
-#if defined(LUA_DEBUG)
-
-
-void *l_Trick = 0;
-
-
-#define obj_at(L,k) s2v(L->ci->func.p + (k))
-
-
-static int runC (lua_State *L, lua_State *L1, const char *pc);
-
-
-static void setnameval (lua_State *L, const char *name, int val) {
- lua_pushinteger(L, val);
- lua_setfield(L, -2, name);
-}
-
-
-static void pushobject (lua_State *L, const TValue *o) {
- setobj2s(L, L->top.p, o);
- api_incr_top(L);
-}
-
-
-static void badexit (const char *fmt, const char *s1, const char *s2) {
- fprintf(stderr, fmt, s1);
- if (s2)
- fprintf(stderr, "extra info: %s\n", s2);
- /* avoid assertion failures when exiting */
- l_memcontrol.numblocks = l_memcontrol.total = 0;
- exit(EXIT_FAILURE);
-}
-
-
-static int tpanic (lua_State *L) {
- const char *msg = (lua_type(L, -1) == LUA_TSTRING)
- ? lua_tostring(L, -1)
- : "error object is not a string";
- return (badexit("PANIC: unprotected error in call to Lua API (%s)\n",
- msg, NULL),
- 0); /* do not return to Lua */
-}
-
-
-/*
-** Warning function for tests. First, it concatenates all parts of
-** a warning in buffer 'buff'. Then, it has three modes:
-** - 0.normal: messages starting with '#' are shown on standard output;
-** - other messages abort the tests (they represent real warning
-** conditions; the standard tests should not generate these conditions
-** unexpectedly);
-** - 1.allow: all messages are shown;
-** - 2.store: all warnings go to the global '_WARN';
-*/
-static void warnf (void *ud, const char *msg, int tocont) {
- lua_State *L = cast(lua_State *, ud);
- static char buff[200] = ""; /* should be enough for tests... */
- static int onoff = 0;
- static int mode = 0; /* start in normal mode */
- static int lasttocont = 0;
- if (!lasttocont && !tocont && *msg == '@') { /* control message? */
- if (buff[0] != '\0')
- badexit("Control warning during warning: %s\naborting...\n", msg, buff);
- if (strcmp(msg, "@off") == 0)
- onoff = 0;
- else if (strcmp(msg, "@on") == 0)
- onoff = 1;
- else if (strcmp(msg, "@normal") == 0)
- mode = 0;
- else if (strcmp(msg, "@allow") == 0)
- mode = 1;
- else if (strcmp(msg, "@store") == 0)
- mode = 2;
- else
- badexit("Invalid control warning in test mode: %s\naborting...\n",
- msg, NULL);
- return;
- }
- lasttocont = tocont;
- if (strlen(msg) >= sizeof(buff) - strlen(buff))
- badexit("warnf-buffer overflow (%s)\n", msg, buff);
- strcat(buff, msg); /* add new message to current warning */
- if (!tocont) { /* message finished? */
- lua_unlock(L);
- luaL_checkstack(L, 1, "warn stack space");
- lua_getglobal(L, "_WARN");
- if (!lua_toboolean(L, -1))
- lua_pop(L, 1); /* ok, no previous unexpected warning */
- else {
- badexit("Unhandled warning in store mode: %s\naborting...\n",
- lua_tostring(L, -1), buff);
- }
- lua_lock(L);
- switch (mode) {
- case 0: { /* normal */
- if (buff[0] != '#' && onoff) /* unexpected warning? */
- badexit("Unexpected warning in test mode: %s\naborting...\n",
- buff, NULL);
- } /* FALLTHROUGH */
- case 1: { /* allow */
- if (onoff)
- fprintf(stderr, "Lua warning: %s\n", buff); /* print warning */
- break;
- }
- case 2: { /* store */
- lua_unlock(L);
- luaL_checkstack(L, 1, "warn stack space");
- lua_pushstring(L, buff);
- lua_setglobal(L, "_WARN"); /* assign message to global '_WARN' */
- lua_lock(L);
- break;
- }
- }
- buff[0] = '\0'; /* prepare buffer for next warning */
- }
-}
-
-
-/*
-** {======================================================================
-** Controlled version for realloc.
-** =======================================================================
-*/
-
-#define MARK 0x55 /* 01010101 (a nice pattern) */
-
-typedef union memHeader {
- LUAI_MAXALIGN;
- struct {
- size_t size;
- int type;
- } d;
-} memHeader;
-
-
-#if !defined(EXTERNMEMCHECK)
-
-/* full memory check */
-#define MARKSIZE 16 /* size of marks after each block */
-#define fillmem(mem,size) memset(mem, -MARK, size)
-
-#else
-
-/* external memory check: don't do it twice */
-#define MARKSIZE 0
-#define fillmem(mem,size) /* empty */
-
-#endif
-
-
-Memcontrol l_memcontrol =
- {0, 0UL, 0UL, 0UL, 0UL, (~0UL),
- {0UL, 0UL, 0UL, 0UL, 0UL, 0UL, 0UL, 0UL, 0UL}};
-
-
-static void freeblock (Memcontrol *mc, memHeader *block) {
- if (block) {
- size_t size = block->d.size;
- int i;
- for (i = 0; i < MARKSIZE; i++) /* check marks after block */
- lua_assert(*(cast_charp(block + 1) + size + i) == MARK);
- mc->objcount[block->d.type]--;
- fillmem(block, sizeof(memHeader) + size + MARKSIZE); /* erase block */
- free(block); /* actually free block */
- mc->numblocks--; /* update counts */
- mc->total -= size;
- }
-}
-
-
-void *debug_realloc (void *ud, void *b, size_t oldsize, size_t size) {
- Memcontrol *mc = cast(Memcontrol *, ud);
- memHeader *block = cast(memHeader *, b);
- int type;
- if (mc->memlimit == 0) { /* first time? */
- char *limit = getenv("MEMLIMIT"); /* initialize memory limit */
- mc->memlimit = limit ? strtoul(limit, NULL, 10) : ULONG_MAX;
- }
- if (block == NULL) {
- type = (oldsize < LUA_NUMTYPES) ? cast_int(oldsize) : 0;
- oldsize = 0;
- }
- else {
- block--; /* go to real header */
- type = block->d.type;
- lua_assert(oldsize == block->d.size);
- }
- if (size == 0) {
- freeblock(mc, block);
- return NULL;
- }
- if (mc->failnext) {
- mc->failnext = 0;
- return NULL; /* fake a single memory allocation error */
- }
- if (mc->countlimit != ~0UL && size != oldsize) { /* count limit in use? */
- if (mc->countlimit == 0)
- return NULL; /* fake a memory allocation error */
- mc->countlimit--;
- }
- if (size > oldsize && mc->total+size-oldsize > mc->memlimit)
- return NULL; /* fake a memory allocation error */
- else {
- memHeader *newblock;
- int i;
- size_t commonsize = (oldsize < size) ? oldsize : size;
- size_t realsize = sizeof(memHeader) + size + MARKSIZE;
- if (realsize < size) return NULL; /* arithmetic overflow! */
- newblock = cast(memHeader *, malloc(realsize)); /* alloc a new block */
- if (newblock == NULL)
- return NULL; /* really out of memory? */
- if (block) {
- memcpy(newblock + 1, block + 1, commonsize); /* copy old contents */
- freeblock(mc, block); /* erase (and check) old copy */
- }
- /* initialize new part of the block with something weird */
- fillmem(cast_charp(newblock + 1) + commonsize, size - commonsize);
- /* initialize marks after block */
- for (i = 0; i < MARKSIZE; i++)
- *(cast_charp(newblock + 1) + size + i) = MARK;
- newblock->d.size = size;
- newblock->d.type = type;
- mc->total += size;
- if (mc->total > mc->maxmem)
- mc->maxmem = mc->total;
- mc->numblocks++;
- mc->objcount[type]++;
- return newblock + 1;
- }
-}
-
-
-/* }====================================================================== */
-
-
-
-/*
-** {=====================================================================
-** Functions to check memory consistency.
-** Most of these checks are done through asserts, so this code does
-** not make sense with asserts off. For this reason, it uses 'assert'
-** directly, instead of 'lua_assert'.
-** ======================================================================
-*/
-
-#include
-
-/*
-** Check GC invariants. For incremental mode, a black object cannot
-** point to a white one. For generational mode, really old objects
-** cannot point to young objects. Both old1 and touched2 objects
-** cannot point to new objects (but can point to survivals).
-** (Threads and open upvalues, despite being marked "really old",
-** continue to be visited in all collections, and therefore can point to
-** new objects. They, and only they, are old but gray.)
-*/
-static int testobjref1 (global_State *g, GCObject *f, GCObject *t) {
- if (isdead(g,t)) return 0;
- if (issweepphase(g))
- return 1; /* no invariants */
- else if (g->gckind != KGC_GENMINOR)
- return !(isblack(f) && iswhite(t)); /* basic incremental invariant */
- else { /* generational mode */
- if ((getage(f) == G_OLD && isblack(f)) && !isold(t))
- return 0;
- if ((getage(f) == G_OLD1 || getage(f) == G_TOUCHED2) &&
- getage(t) == G_NEW)
- return 0;
- return 1;
- }
-}
-
-
-static void printobj (global_State *g, GCObject *o) {
- printf("||%s(%p)-%c%c(%02X)||",
- ttypename(novariant(o->tt)), (void *)o,
- isdead(g,o) ? 'd' : isblack(o) ? 'b' : iswhite(o) ? 'w' : 'g',
- "ns01oTt"[getage(o)], o->marked);
- if (o->tt == LUA_VSHRSTR || o->tt == LUA_VLNGSTR)
- printf(" '%s'", getstr(gco2ts(o)));
-}
-
-
-void lua_printobj (lua_State *L, struct GCObject *o) {
- printobj(G(L), o);
-}
-
-
-void lua_printvalue (TValue *v) {
- switch (ttypetag(v)) {
- case LUA_VNUMINT: case LUA_VNUMFLT: {
- char buff[LUA_N2SBUFFSZ];
- unsigned len = luaO_tostringbuff(v, buff);
- buff[len] = '\0';
- printf("%s", buff);
- break;
- }
- case LUA_VSHRSTR:
- printf("'%s'", getstr(tsvalue(v))); break;
- case LUA_VLNGSTR:
- printf("'%.30s...'", getstr(tsvalue(v))); break;
- case LUA_VFALSE:
- printf("%s", "false"); break;
- case LUA_VTRUE:
- printf("%s", "true"); break;
- case LUA_VLIGHTUSERDATA:
- printf("light udata: %p", pvalue(v)); break;
- case LUA_VUSERDATA:
- printf("full udata: %p", uvalue(v)); break;
- case LUA_VNIL:
- printf("nil"); break;
- case LUA_VLCF:
- printf("light C function: %p", fvalue(v)); break;
- case LUA_VCCL:
- printf("C closure: %p", clCvalue(v)); break;
- case LUA_VLCL:
- printf("Lua function: %p", clLvalue(v)); break;
- case LUA_VTHREAD:
- printf("thread: %p", thvalue(v)); break;
- case LUA_VTABLE:
- printf("table: %p", hvalue(v)); break;
- default:
- lua_assert(0);
- }
-}
-
-
-static int testobjref (global_State *g, GCObject *f, GCObject *t) {
- int r1 = testobjref1(g, f, t);
- if (!r1) {
- printf("%d(%02X) - ", g->gcstate, g->currentwhite);
- printobj(g, f);
- printf(" -> ");
- printobj(g, t);
- printf("\n");
- }
- return r1;
-}
-
-
-static void checkobjref (global_State *g, GCObject *f, GCObject *t) {
- assert(testobjref(g, f, t));
-}
-
-
-/*
-** Version where 't' can be NULL. In that case, it should not apply the
-** macro 'obj2gco' over the object. ('t' may have several types, so this
-** definition must be a macro.) Most checks need this version, because
-** the check may run while an object is still being created.
-*/
-#define checkobjrefN(g,f,t) { if (t) checkobjref(g,f,obj2gco(t)); }
-
-
-static void checkvalref (global_State *g, GCObject *f, const TValue *t) {
- assert(!iscollectable(t) || (righttt(t) && testobjref(g, f, gcvalue(t))));
-}
-
-
-static void checktable (global_State *g, Table *h) {
- unsigned int i;
- unsigned int asize = h->asize;
- Node *n, *limit = gnode(h, sizenode(h));
- GCObject *hgc = obj2gco(h);
- checkobjrefN(g, hgc, h->metatable);
- for (i = 0; i < asize; i++) {
- TValue aux;
- arr2obj(h, i, &aux);
- checkvalref(g, hgc, &aux);
- }
- for (n = gnode(h, 0); n < limit; n++) {
- if (!isempty(gval(n))) {
- TValue k;
- getnodekey(mainthread(g), &k, n);
- assert(!keyisnil(n));
- checkvalref(g, hgc, &k);
- checkvalref(g, hgc, gval(n));
- }
- }
-}
-
-
-static void checkudata (global_State *g, Udata *u) {
- int i;
- GCObject *hgc = obj2gco(u);
- checkobjrefN(g, hgc, u->metatable);
- for (i = 0; i < u->nuvalue; i++)
- checkvalref(g, hgc, &u->uv[i].uv);
-}
-
-
-static void checkproto (global_State *g, Proto *f) {
- int i;
- GCObject *fgc = obj2gco(f);
- checkobjrefN(g, fgc, f->source);
- for (i=0; isizek; i++) {
- if (iscollectable(f->k + i))
- checkobjref(g, fgc, gcvalue(f->k + i));
- }
- for (i=0; isizeupvalues; i++)
- checkobjrefN(g, fgc, f->upvalues[i].name);
- for (i=0; isizep; i++)
- checkobjrefN(g, fgc, f->p[i]);
- for (i=0; isizelocvars; i++)
- checkobjrefN(g, fgc, f->locvars[i].varname);
-}
-
-
-static void checkCclosure (global_State *g, CClosure *cl) {
- GCObject *clgc = obj2gco(cl);
- int i;
- for (i = 0; i < cl->nupvalues; i++)
- checkvalref(g, clgc, &cl->upvalue[i]);
-}
-
-
-static void checkLclosure (global_State *g, LClosure *cl) {
- GCObject *clgc = obj2gco(cl);
- int i;
- checkobjrefN(g, clgc, cl->p);
- for (i=0; inupvalues; i++) {
- UpVal *uv = cl->upvals[i];
- if (uv) {
- checkobjrefN(g, clgc, uv);
- if (!upisopen(uv))
- checkvalref(g, obj2gco(uv), uv->v.p);
- }
- }
-}
-
-
-static int lua_checkpc (CallInfo *ci) {
- if (!isLua(ci)) return 1;
- else {
- StkId f = ci->func.p;
- Proto *p = clLvalue(s2v(f))->p;
- return p->code <= ci->u.l.savedpc &&
- ci->u.l.savedpc <= p->code + p->sizecode;
- }
-}
-
-
-static void check_stack (global_State *g, lua_State *L1) {
- StkId o;
- CallInfo *ci;
- UpVal *uv;
- assert(!isdead(g, L1));
- if (L1->stack.p == NULL) { /* incomplete thread? */
- assert(L1->openupval == NULL && L1->ci == NULL);
- return;
- }
- for (uv = L1->openupval; uv != NULL; uv = uv->u.open.next)
- assert(upisopen(uv)); /* must be open */
- assert(L1->top.p <= L1->stack_last.p);
- assert(L1->tbclist.p <= L1->top.p);
- for (ci = L1->ci; ci != NULL; ci = ci->previous) {
- assert(ci->top.p <= L1->stack_last.p);
- assert(lua_checkpc(ci));
- }
- for (o = L1->stack.p; o < L1->stack_last.p; o++)
- checkliveness(L1, s2v(o)); /* entire stack must have valid values */
-}
-
-
-static void checkrefs (global_State *g, GCObject *o) {
- switch (o->tt) {
- case LUA_VUSERDATA: {
- checkudata(g, gco2u(o));
- break;
- }
- case LUA_VUPVAL: {
- checkvalref(g, o, gco2upv(o)->v.p);
- break;
- }
- case LUA_VTABLE: {
- checktable(g, gco2t(o));
- break;
- }
- case LUA_VTHREAD: {
- check_stack(g, gco2th(o));
- break;
- }
- case LUA_VLCL: {
- checkLclosure(g, gco2lcl(o));
- break;
- }
- case LUA_VCCL: {
- checkCclosure(g, gco2ccl(o));
- break;
- }
- case LUA_VPROTO: {
- checkproto(g, gco2p(o));
- break;
- }
- case LUA_VSHRSTR:
- case LUA_VLNGSTR: {
- assert(!isgray(o)); /* strings are never gray */
- break;
- }
- default: assert(0);
- }
-}
-
-
-/*
-** Check consistency of an object:
-** - Dead objects can only happen in the 'allgc' list during a sweep
-** phase (controlled by the caller through 'maybedead').
-** - During pause, all objects must be white.
-** - In generational mode:
-** * objects must be old enough for their lists ('listage').
-** * old objects cannot be white.
-** * old objects must be black, except for 'touched1', 'old0',
-** threads, and open upvalues.
-** * 'touched1' objects must be gray.
-*/
-static void checkobject (global_State *g, GCObject *o, int maybedead,
- int listage) {
- if (isdead(g, o))
- assert(maybedead);
- else {
- assert(g->gcstate != GCSpause || iswhite(o));
- if (g->gckind == KGC_GENMINOR) { /* generational mode? */
- assert(getage(o) >= listage);
- if (isold(o)) {
- assert(!iswhite(o));
- assert(isblack(o) ||
- getage(o) == G_TOUCHED1 ||
- getage(o) == G_OLD0 ||
- o->tt == LUA_VTHREAD ||
- (o->tt == LUA_VUPVAL && upisopen(gco2upv(o))));
- }
- assert(getage(o) != G_TOUCHED1 || isgray(o));
- }
- checkrefs(g, o);
- }
-}
-
-
-static l_mem checkgraylist (global_State *g, GCObject *o) {
- int total = 0; /* count number of elements in the list */
- cast_void(g); /* better to keep it if we need to print an object */
- while (o) {
- assert(!!isgray(o) ^ (getage(o) == G_TOUCHED2));
- assert(!testbit(o->marked, TESTBIT));
- if (keepinvariant(g))
- l_setbit(o->marked, TESTBIT); /* mark that object is in a gray list */
- total++;
- switch (o->tt) {
- case LUA_VTABLE: o = gco2t(o)->gclist; break;
- case LUA_VLCL: o = gco2lcl(o)->gclist; break;
- case LUA_VCCL: o = gco2ccl(o)->gclist; break;
- case LUA_VTHREAD: o = gco2th(o)->gclist; break;
- case LUA_VPROTO: o = gco2p(o)->gclist; break;
- case LUA_VUSERDATA:
- assert(gco2u(o)->nuvalue > 0);
- o = gco2u(o)->gclist;
- break;
- default: assert(0); /* other objects cannot be in a gray list */
- }
- }
- return total;
-}
-
-
-/*
-** Check objects in gray lists.
-*/
-static l_mem checkgrays (global_State *g) {
- l_mem total = 0; /* count number of elements in all lists */
- if (!keepinvariant(g)) return total;
- total += checkgraylist(g, g->gray);
- total += checkgraylist(g, g->grayagain);
- total += checkgraylist(g, g->weak);
- total += checkgraylist(g, g->allweak);
- total += checkgraylist(g, g->ephemeron);
- return total;
-}
-
-
-/*
-** Check whether 'o' should be in a gray list. If so, increment
-** 'count' and check its TESTBIT. (It must have been previously set by
-** 'checkgraylist'.)
-*/
-static void incifingray (global_State *g, GCObject *o, l_mem *count) {
- if (!keepinvariant(g))
- return; /* gray lists not being kept in these phases */
- if (o->tt == LUA_VUPVAL) {
- /* only open upvalues can be gray */
- assert(!isgray(o) || upisopen(gco2upv(o)));
- return; /* upvalues are never in gray lists */
- }
- /* these are the ones that must be in gray lists */
- if (isgray(o) || getage(o) == G_TOUCHED2) {
- (*count)++;
- assert(testbit(o->marked, TESTBIT));
- resetbit(o->marked, TESTBIT); /* prepare for next cycle */
- }
-}
-
-
-static l_mem checklist (global_State *g, int maybedead, int tof,
- GCObject *newl, GCObject *survival, GCObject *old, GCObject *reallyold) {
- GCObject *o;
- l_mem total = 0; /* number of object that should be in gray lists */
- for (o = newl; o != survival; o = o->next) {
- checkobject(g, o, maybedead, G_NEW);
- incifingray(g, o, &total);
- assert(!tof == !tofinalize(o));
- }
- for (o = survival; o != old; o = o->next) {
- checkobject(g, o, 0, G_SURVIVAL);
- incifingray(g, o, &total);
- assert(!tof == !tofinalize(o));
- }
- for (o = old; o != reallyold; o = o->next) {
- checkobject(g, o, 0, G_OLD1);
- incifingray(g, o, &total);
- assert(!tof == !tofinalize(o));
- }
- for (o = reallyold; o != NULL; o = o->next) {
- checkobject(g, o, 0, G_OLD);
- incifingray(g, o, &total);
- assert(!tof == !tofinalize(o));
- }
- return total;
-}
-
-
-int lua_checkmemory (lua_State *L) {
- global_State *g = G(L);
- GCObject *o;
- int maybedead;
- l_mem totalin; /* total of objects that are in gray lists */
- l_mem totalshould; /* total of objects that should be in gray lists */
- if (keepinvariant(g)) {
- assert(!iswhite(mainthread(g)));
- assert(!iswhite(gcvalue(&g->l_registry)));
- }
- assert(!isdead(g, gcvalue(&g->l_registry)));
- assert(g->sweepgc == NULL || issweepphase(g));
- totalin = checkgrays(g);
-
- /* check 'fixedgc' list */
- for (o = g->fixedgc; o != NULL; o = o->next) {
- assert(o->tt == LUA_VSHRSTR && isgray(o) && getage(o) == G_OLD);
- }
-
- /* check 'allgc' list */
- maybedead = (GCSatomic < g->gcstate && g->gcstate <= GCSswpallgc);
- totalshould = checklist(g, maybedead, 0, g->allgc,
- g->survival, g->old1, g->reallyold);
-
- /* check 'finobj' list */
- totalshould += checklist(g, 0, 1, g->finobj,
- g->finobjsur, g->finobjold1, g->finobjrold);
-
- /* check 'tobefnz' list */
- for (o = g->tobefnz; o != NULL; o = o->next) {
- checkobject(g, o, 0, G_NEW);
- incifingray(g, o, &totalshould);
- assert(tofinalize(o));
- assert(o->tt == LUA_VUSERDATA || o->tt == LUA_VTABLE);
- }
- if (keepinvariant(g))
- assert(totalin == totalshould);
- return 0;
-}
-
-/* }====================================================== */
-
-
-
-/*
-** {======================================================
-** Disassembler
-** =======================================================
-*/
-
-
-static char *buildop (Proto *p, int pc, char *buff) {
- char *obuff = buff;
- Instruction i = p->code[pc];
- OpCode o = GET_OPCODE(i);
- const char *name = opnames[o];
- int line = luaG_getfuncline(p, pc);
- int lineinfo = (p->lineinfo != NULL) ? p->lineinfo[pc] : 0;
- if (lineinfo == ABSLINEINFO)
- buff += sprintf(buff, "(__");
- else
- buff += sprintf(buff, "(%2d", lineinfo);
- buff += sprintf(buff, " - %4d) %4d - ", line, pc);
- switch (getOpMode(o)) {
- case iABC:
- sprintf(buff, "%-12s%4d %4d %4d%s", name,
- GETARG_A(i), GETARG_B(i), GETARG_C(i),
- GETARG_k(i) ? " (k)" : "");
- break;
- case ivABC:
- sprintf(buff, "%-12s%4d %4d %4d%s", name,
- GETARG_A(i), GETARG_vB(i), GETARG_vC(i),
- GETARG_k(i) ? " (k)" : "");
- break;
- case iABx:
- sprintf(buff, "%-12s%4d %4d", name, GETARG_A(i), GETARG_Bx(i));
- break;
- case iAsBx:
- sprintf(buff, "%-12s%4d %4d", name, GETARG_A(i), GETARG_sBx(i));
- break;
- case iAx:
- sprintf(buff, "%-12s%4d", name, GETARG_Ax(i));
- break;
- case isJ:
- sprintf(buff, "%-12s%4d", name, GETARG_sJ(i));
- break;
- }
- return obuff;
-}
-
-
-#if 0
-void luaI_printcode (Proto *pt, int size) {
- int pc;
- for (pc=0; pcmaxstacksize);
- setnameval(L, "numparams", p->numparams);
- for (pc=0; pcsizecode; pc++) {
- char buff[100];
- lua_pushinteger(L, pc+1);
- lua_pushstring(L, buildop(p, pc, buff));
- lua_settable(L, -3);
- }
- return 1;
-}
-
-
-static int printcode (lua_State *L) {
- int pc;
- Proto *p;
- luaL_argcheck(L, lua_isfunction(L, 1) && !lua_iscfunction(L, 1),
- 1, "Lua function expected");
- p = getproto(obj_at(L, 1));
- printf("maxstack: %d\n", p->maxstacksize);
- printf("numparams: %d\n", p->numparams);
- for (pc=0; pcsizecode; pc++) {
- char buff[100];
- printf("%s\n", buildop(p, pc, buff));
- }
- return 0;
-}
-
-
-static int listk (lua_State *L) {
- Proto *p;
- int i;
- luaL_argcheck(L, lua_isfunction(L, 1) && !lua_iscfunction(L, 1),
- 1, "Lua function expected");
- p = getproto(obj_at(L, 1));
- lua_createtable(L, p->sizek, 0);
- for (i=0; isizek; i++) {
- pushobject(L, p->k+i);
- lua_rawseti(L, -2, i+1);
- }
- return 1;
-}
-
-
-static int listabslineinfo (lua_State *L) {
- Proto *p;
- int i;
- luaL_argcheck(L, lua_isfunction(L, 1) && !lua_iscfunction(L, 1),
- 1, "Lua function expected");
- p = getproto(obj_at(L, 1));
- luaL_argcheck(L, p->abslineinfo != NULL, 1, "function has no debug info");
- lua_createtable(L, 2 * p->sizeabslineinfo, 0);
- for (i=0; i < p->sizeabslineinfo; i++) {
- lua_pushinteger(L, p->abslineinfo[i].pc);
- lua_rawseti(L, -2, 2 * i + 1);
- lua_pushinteger(L, p->abslineinfo[i].line);
- lua_rawseti(L, -2, 2 * i + 2);
- }
- return 1;
-}
-
-
-static int listlocals (lua_State *L) {
- Proto *p;
- int pc = cast_int(luaL_checkinteger(L, 2)) - 1;
- int i = 0;
- const char *name;
- luaL_argcheck(L, lua_isfunction(L, 1) && !lua_iscfunction(L, 1),
- 1, "Lua function expected");
- p = getproto(obj_at(L, 1));
- while ((name = luaF_getlocalname(p, ++i, pc)) != NULL)
- lua_pushstring(L, name);
- return i-1;
-}
-
-/* }====================================================== */
-
-
-
-void lua_printstack (lua_State *L) {
- int i;
- int n = lua_gettop(L);
- printf("stack: >>\n");
- for (i = 1; i <= n; i++) {
- printf("%3d: ", i);
- lua_printvalue(s2v(L->ci->func.p + i));
- printf("\n");
- }
- printf("<<\n");
-}
-
-
-int lua_printallstack (lua_State *L) {
- StkId p;
- int i = 1;
- CallInfo *ci = &L->base_ci;
- printf("stack: >>\n");
- for (p = L->stack.p; p < L->top.p; p++) {
- if (ci != NULL && p == ci->func.p) {
- printf(" ---\n");
- if (ci == L->ci)
- ci = NULL; /* printed last frame */
- else
- ci = ci->next;
- }
- printf("%3d: ", i++);
- lua_printvalue(s2v(p));
- printf("\n");
- }
- printf("<<\n");
- return 0;
-}
-
-
-static int get_limits (lua_State *L) {
- lua_createtable(L, 0, 5);
- setnameval(L, "IS32INT", LUAI_IS32INT);
- setnameval(L, "MAXARG_Ax", MAXARG_Ax);
- setnameval(L, "MAXARG_Bx", MAXARG_Bx);
- setnameval(L, "OFFSET_sBx", OFFSET_sBx);
- setnameval(L, "NUM_OPCODES", NUM_OPCODES);
- return 1;
-}
-
-
-static int get_sizes (lua_State *L) {
- lua_newtable(L);
- setnameval(L, "Lua state", sizeof(lua_State));
- setnameval(L, "global state", sizeof(global_State));
- setnameval(L, "TValue", sizeof(TValue));
- setnameval(L, "Node", sizeof(Node));
- setnameval(L, "stack Value", sizeof(StackValue));
- return 1;
-}
-
-
-static int mem_query (lua_State *L) {
- if (lua_isnone(L, 1)) {
- lua_pushinteger(L, cast_Integer(l_memcontrol.total));
- lua_pushinteger(L, cast_Integer(l_memcontrol.numblocks));
- lua_pushinteger(L, cast_Integer(l_memcontrol.maxmem));
- return 3;
- }
- else if (lua_isnumber(L, 1)) {
- unsigned long limit = cast(unsigned long, luaL_checkinteger(L, 1));
- if (limit == 0) limit = ULONG_MAX;
- l_memcontrol.memlimit = limit;
- return 0;
- }
- else {
- const char *t = luaL_checkstring(L, 1);
- int i;
- for (i = LUA_NUMTYPES - 1; i >= 0; i--) {
- if (strcmp(t, ttypename(i)) == 0) {
- lua_pushinteger(L, cast_Integer(l_memcontrol.objcount[i]));
- return 1;
- }
- }
- return luaL_error(L, "unknown type '%s'", t);
- }
-}
-
-
-static int alloc_count (lua_State *L) {
- if (lua_isnone(L, 1))
- l_memcontrol.countlimit = cast(unsigned long, ~0L);
- else
- l_memcontrol.countlimit = cast(unsigned long, luaL_checkinteger(L, 1));
- return 0;
-}
-
-
-static int alloc_failnext (lua_State *L) {
- UNUSED(L);
- l_memcontrol.failnext = 1;
- return 0;
-}
-
-
-static int settrick (lua_State *L) {
- if (ttisnil(obj_at(L, 1)))
- l_Trick = NULL;
- else
- l_Trick = gcvalue(obj_at(L, 1));
- return 0;
-}
-
-
-static int gc_color (lua_State *L) {
- TValue *o;
- luaL_checkany(L, 1);
- o = obj_at(L, 1);
- if (!iscollectable(o))
- lua_pushstring(L, "no collectable");
- else {
- GCObject *obj = gcvalue(o);
- lua_pushstring(L, isdead(G(L), obj) ? "dead" :
- iswhite(obj) ? "white" :
- isblack(obj) ? "black" : "gray");
- }
- return 1;
-}
-
-
-static int gc_age (lua_State *L) {
- TValue *o;
- luaL_checkany(L, 1);
- o = obj_at(L, 1);
- if (!iscollectable(o))
- lua_pushstring(L, "no collectable");
- else {
- static const char *gennames[] = {"new", "survival", "old0", "old1",
- "old", "touched1", "touched2"};
- GCObject *obj = gcvalue(o);
- lua_pushstring(L, gennames[getage(obj)]);
- }
- return 1;
-}
-
-
-static int gc_printobj (lua_State *L) {
- TValue *o;
- luaL_checkany(L, 1);
- o = obj_at(L, 1);
- if (!iscollectable(o))
- printf("no collectable\n");
- else {
- GCObject *obj = gcvalue(o);
- printobj(G(L), obj);
- printf("\n");
- }
- return 0;
-}
-
-
-static const char *const statenames[] = {
- "propagate", "enteratomic", "atomic", "sweepallgc", "sweepfinobj",
- "sweeptobefnz", "sweepend", "callfin", "pause", ""};
-
-static int gc_state (lua_State *L) {
- static const int states[] = {
- GCSpropagate, GCSenteratomic, GCSatomic, GCSswpallgc, GCSswpfinobj,
- GCSswptobefnz, GCSswpend, GCScallfin, GCSpause, -1};
- int option = states[luaL_checkoption(L, 1, "", statenames)];
- global_State *g = G(L);
- if (option == -1) {
- lua_pushstring(L, statenames[g->gcstate]);
- return 1;
- }
- else {
- if (g->gckind != KGC_INC)
- luaL_error(L, "cannot change states in generational mode");
- lua_lock(L);
- if (option < g->gcstate) { /* must cross 'pause'? */
- luaC_runtilstate(L, GCSpause, 1); /* run until pause */
- }
- luaC_runtilstate(L, option, 0); /* do not skip propagation state */
- lua_assert(g->gcstate == option);
- lua_unlock(L);
- return 0;
- }
-}
-
-
-static int tracinggc = 0;
-void luai_tracegctest (lua_State *L, int first) {
- if (!tracinggc) return;
- else {
- global_State *g = G(L);
- lua_unlock(L);
- g->gcstp = GCSTPGC;
- lua_checkstack(L, 10);
- lua_getfield(L, LUA_REGISTRYINDEX, "tracegc");
- lua_pushboolean(L, first);
- lua_call(L, 1, 0);
- g->gcstp = 0;
- lua_lock(L);
- }
-}
-
-
-static int tracegc (lua_State *L) {
- if (lua_isnil(L, 1))
- tracinggc = 0;
- else {
- tracinggc = 1;
- lua_setfield(L, LUA_REGISTRYINDEX, "tracegc");
- }
- return 0;
-}
-
-
-static int hash_query (lua_State *L) {
- if (lua_isnone(L, 2)) {
- TString *ts;
- luaL_argcheck(L, lua_type(L, 1) == LUA_TSTRING, 1, "string expected");
- ts = tsvalue(obj_at(L, 1));
- if (ts->tt == LUA_VLNGSTR)
- luaS_hashlongstr(ts); /* make sure long string has a hash */
- lua_pushinteger(L, cast_int(ts->hash));
- }
- else {
- TValue *o = obj_at(L, 1);
- Table *t;
- luaL_checktype(L, 2, LUA_TTABLE);
- t = hvalue(obj_at(L, 2));
- lua_pushinteger(L, cast_Integer(luaH_mainposition(t, o) - t->node));
- }
- return 1;
-}
-
-
-static int stacklevel (lua_State *L) {
- int a = 0;
- lua_pushinteger(L, cast_Integer(L->top.p - L->stack.p));
- lua_pushinteger(L, stacksize(L));
- lua_pushinteger(L, cast_Integer(L->nCcalls));
- lua_pushinteger(L, L->nci);
- lua_pushinteger(L, (lua_Integer)(size_t)&a);
- return 5;
-}
-
-
-static int resetCI (lua_State *L) {
- CallInfo *ci = L->ci;
- while (ci->next != NULL) {
- CallInfo *tofree = ci->next;
- ci->next = ci->next->next;
- luaM_free(L, tofree);
- L->nci--;
- }
- return 0;
-}
-
-
-static int reallocstack (lua_State *L) {
- int n = cast_int(luaL_checkinteger(L, 1));
- lua_lock(L);
- luaD_reallocstack(L, cast_int(L->top.p - L->stack.p) + n, 1);
- lua_unlock(L);
- return 0;
-}
-
-
-static int table_query (lua_State *L) {
- const Table *t;
- int i = cast_int(luaL_optinteger(L, 2, -1));
- unsigned int asize;
- luaL_checktype(L, 1, LUA_TTABLE);
- t = hvalue(obj_at(L, 1));
- asize = t->asize;
- if (i == -1) {
- lua_pushinteger(L, cast_Integer(asize));
- lua_pushinteger(L, cast_Integer(allocsizenode(t)));
- lua_pushinteger(L, cast_Integer(asize > 0 ? *lenhint(t) : 0));
- return 3;
- }
- else if (cast_uint(i) < asize) {
- lua_pushinteger(L, i);
- if (!tagisempty(*getArrTag(t, i)))
- arr2obj(t, cast_uint(i), s2v(L->top.p));
- else
- setnilvalue(s2v(L->top.p));
- api_incr_top(L);
- lua_pushnil(L);
- }
- else if (cast_uint(i -= cast_int(asize)) < sizenode(t)) {
- TValue k;
- getnodekey(L, &k, gnode(t, i));
- if (!isempty(gval(gnode(t, i))) ||
- ttisnil(&k) ||
- ttisnumber(&k)) {
- pushobject(L, &k);
- }
- else
- lua_pushliteral(L, "");
- if (!isempty(gval(gnode(t, i))))
- pushobject(L, gval(gnode(t, i)));
- else
- lua_pushnil(L);
- lua_pushinteger(L, gnext(&t->node[i]));
- }
- return 3;
-}
-
-
-static int gc_query (lua_State *L) {
- global_State *g = G(L);
- lua_pushstring(L, g->gckind == KGC_INC ? "inc"
- : g->gckind == KGC_GENMAJOR ? "genmajor"
- : "genminor");
- lua_pushstring(L, statenames[g->gcstate]);
- lua_pushinteger(L, cast_st2S(gettotalbytes(g)));
- lua_pushinteger(L, cast_st2S(g->GCdebt));
- lua_pushinteger(L, cast_st2S(g->GCmarked));
- lua_pushinteger(L, cast_st2S(g->GCmajorminor));
- return 6;
-}
-
-
-static int test_codeparam (lua_State *L) {
- lua_Integer p = luaL_checkinteger(L, 1);
- lua_pushinteger(L, luaO_codeparam(cast_uint(p)));
- return 1;
-}
-
-
-static int test_applyparam (lua_State *L) {
- lua_Integer p = luaL_checkinteger(L, 1);
- lua_Integer x = luaL_checkinteger(L, 2);
- lua_pushinteger(L, cast_Integer(luaO_applyparam(cast_byte(p), x)));
- return 1;
-}
-
-
-static int string_query (lua_State *L) {
- stringtable *tb = &G(L)->strt;
- int s = cast_int(luaL_optinteger(L, 1, 0)) - 1;
- if (s == -1) {
- lua_pushinteger(L ,tb->size);
- lua_pushinteger(L ,tb->nuse);
- return 2;
- }
- else if (s < tb->size) {
- TString *ts;
- int n = 0;
- for (ts = tb->hash[s]; ts != NULL; ts = ts->u.hnext) {
- setsvalue2s(L, L->top.p, ts);
- api_incr_top(L);
- n++;
- }
- return n;
- }
- else return 0;
-}
-
-
-static int getreftable (lua_State *L) {
- if (lua_istable(L, 2)) /* is there a table as second argument? */
- return 2; /* use it as the table */
- else
- return LUA_REGISTRYINDEX; /* default is to use the register */
-}
-
-
-static int tref (lua_State *L) {
- int t = getreftable(L);
- int level = lua_gettop(L);
- luaL_checkany(L, 1);
- lua_pushvalue(L, 1);
- lua_pushinteger(L, luaL_ref(L, t));
- cast_void(level); /* to avoid warnings */
- lua_assert(lua_gettop(L) == level+1); /* +1 for result */
- return 1;
-}
-
-
-static int getref (lua_State *L) {
- int t = getreftable(L);
- int level = lua_gettop(L);
- lua_rawgeti(L, t, luaL_checkinteger(L, 1));
- cast_void(level); /* to avoid warnings */
- lua_assert(lua_gettop(L) == level+1);
- return 1;
-}
-
-static int unref (lua_State *L) {
- int t = getreftable(L);
- int level = lua_gettop(L);
- luaL_unref(L, t, cast_int(luaL_checkinteger(L, 1)));
- cast_void(level); /* to avoid warnings */
- lua_assert(lua_gettop(L) == level);
- return 0;
-}
-
-
-static int upvalue (lua_State *L) {
- int n = cast_int(luaL_checkinteger(L, 2));
- luaL_checktype(L, 1, LUA_TFUNCTION);
- if (lua_isnone(L, 3)) {
- const char *name = lua_getupvalue(L, 1, n);
- if (name == NULL) return 0;
- lua_pushstring(L, name);
- return 2;
- }
- else {
- const char *name = lua_setupvalue(L, 1, n);
- lua_pushstring(L, name);
- return 1;
- }
-}
-
-
-static int newuserdata (lua_State *L) {
- size_t size = cast_sizet(luaL_optinteger(L, 1, 0));
- int nuv = cast_int(luaL_optinteger(L, 2, 0));
- char *p = cast_charp(lua_newuserdatauv(L, size, nuv));
- while (size--) *p++ = '\0';
- return 1;
-}
-
-
-static int pushuserdata (lua_State *L) {
- lua_Integer u = luaL_checkinteger(L, 1);
- lua_pushlightuserdata(L, cast_voidp(cast_sizet(u)));
- return 1;
-}
-
-
-static int udataval (lua_State *L) {
- lua_pushinteger(L, cast_st2S(cast_sizet(lua_touserdata(L, 1))));
- return 1;
-}
-
-
-static int doonnewstack (lua_State *L) {
- lua_State *L1 = lua_newthread(L);
- size_t l;
- const char *s = luaL_checklstring(L, 1, &l);
- int status = luaL_loadbuffer(L1, s, l, s);
- if (status == LUA_OK)
- status = lua_pcall(L1, 0, 0, 0);
- lua_pushinteger(L, status);
- return 1;
-}
-
-
-static int s2d (lua_State *L) {
- lua_pushnumber(L, cast_num(*cast(const double *, luaL_checkstring(L, 1))));
- return 1;
-}
-
-
-static int d2s (lua_State *L) {
- double d = cast(double, luaL_checknumber(L, 1));
- lua_pushlstring(L, cast_charp(&d), sizeof(d));
- return 1;
-}
-
-
-static int num2int (lua_State *L) {
- lua_pushinteger(L, lua_tointeger(L, 1));
- return 1;
-}
-
-
-static int makeseed (lua_State *L) {
- lua_pushinteger(L, cast_Integer(luaL_makeseed(L)));
- return 1;
-}
-
-
-static int newstate (lua_State *L) {
- void *ud;
- lua_Alloc f = lua_getallocf(L, &ud);
- lua_State *L1 = lua_newstate(f, ud, 0);
- if (L1) {
- lua_atpanic(L1, tpanic);
- lua_pushlightuserdata(L, L1);
- }
- else
- lua_pushnil(L);
- return 1;
-}
-
-
-static lua_State *getstate (lua_State *L) {
- lua_State *L1 = cast(lua_State *, lua_touserdata(L, 1));
- luaL_argcheck(L, L1 != NULL, 1, "state expected");
- return L1;
-}
-
-
-static int loadlib (lua_State *L) {
- lua_State *L1 = getstate(L);
- int load = cast_int(luaL_checkinteger(L, 2));
- int preload = cast_int(luaL_checkinteger(L, 3));
- luaL_openselectedlibs(L1, load, preload);
- luaL_requiref(L1, "T", luaB_opentests, 0);
- lua_assert(lua_type(L1, -1) == LUA_TTABLE);
- /* 'requiref' should not reload module already loaded... */
- luaL_requiref(L1, "T", NULL, 1); /* seg. fault if it reloads */
- /* ...but should return the same module */
- lua_assert(lua_compare(L1, -1, -2, LUA_OPEQ));
- return 0;
-}
-
-static int closestate (lua_State *L) {
- lua_State *L1 = getstate(L);
- lua_close(L1);
- return 0;
-}
-
-static int doremote (lua_State *L) {
- lua_State *L1 = getstate(L);
- size_t lcode;
- const char *code = luaL_checklstring(L, 2, &lcode);
- int status;
- lua_settop(L1, 0);
- status = luaL_loadbuffer(L1, code, lcode, code);
- if (status == LUA_OK)
- status = lua_pcall(L1, 0, LUA_MULTRET, 0);
- if (status != LUA_OK) {
- lua_pushnil(L);
- lua_pushstring(L, lua_tostring(L1, -1));
- lua_pushinteger(L, status);
- return 3;
- }
- else {
- int i = 0;
- while (!lua_isnone(L1, ++i))
- lua_pushstring(L, lua_tostring(L1, i));
- lua_pop(L1, i-1);
- return i-1;
- }
-}
-
-
-static int log2_aux (lua_State *L) {
- unsigned int x = (unsigned int)luaL_checkinteger(L, 1);
- lua_pushinteger(L, luaO_ceillog2(x));
- return 1;
-}
-
-
-struct Aux { jmp_buf jb; const char *paniccode; lua_State *L; };
-
-/*
-** does a long-jump back to "main program".
-*/
-static int panicback (lua_State *L) {
- struct Aux *b;
- lua_checkstack(L, 1); /* open space for 'Aux' struct */
- lua_getfield(L, LUA_REGISTRYINDEX, "_jmpbuf"); /* get 'Aux' struct */
- b = (struct Aux *)lua_touserdata(L, -1);
- lua_pop(L, 1); /* remove 'Aux' struct */
- runC(b->L, L, b->paniccode); /* run optional panic code */
- longjmp(b->jb, 1);
- return 1; /* to avoid warnings */
-}
-
-static int checkpanic (lua_State *L) {
- struct Aux b;
- void *ud;
- lua_State *L1;
- const char *code = luaL_checkstring(L, 1);
- lua_Alloc f = lua_getallocf(L, &ud);
- b.paniccode = luaL_optstring(L, 2, "");
- b.L = L;
- L1 = lua_newstate(f, ud, 0); /* create new state */
- if (L1 == NULL) { /* error? */
- lua_pushstring(L, MEMERRMSG);
- return 1;
- }
- lua_atpanic(L1, panicback); /* set its panic function */
- lua_pushlightuserdata(L1, &b);
- lua_setfield(L1, LUA_REGISTRYINDEX, "_jmpbuf"); /* store 'Aux' struct */
- if (setjmp(b.jb) == 0) { /* set jump buffer */
- runC(L, L1, code); /* run code unprotected */
- lua_pushliteral(L, "no errors");
- }
- else { /* error handling */
- /* move error message to original state */
- lua_pushstring(L, lua_tostring(L1, -1));
- }
- lua_close(L1);
- return 1;
-}
-
-
-static int externKstr (lua_State *L) {
- size_t len;
- const char *s = luaL_checklstring(L, 1, &len);
- lua_pushexternalstring(L, s, len, NULL, NULL);
- return 1;
-}
-
-
-/*
-** Create a buffer with the content of a given string and then
-** create an external string using that buffer. Use the allocation
-** function from Lua to create and free the buffer.
-*/
-static int externstr (lua_State *L) {
- size_t len;
- const char *s = luaL_checklstring(L, 1, &len);
- void *ud;
- lua_Alloc allocf = lua_getallocf(L, &ud); /* get allocation function */
- /* create the buffer */
- char *buff = cast_charp((*allocf)(ud, NULL, 0, len + 1));
- if (buff == NULL) { /* memory error? */
- lua_pushliteral(L, "not enough memory");
- lua_error(L); /* raise a memory error */
- }
- /* copy string content to buffer, including ending 0 */
- memcpy(buff, s, (len + 1) * sizeof(char));
- /* create external string */
- lua_pushexternalstring(L, buff, len, allocf, ud);
- return 1;
-}
-
-
-/*
-** {====================================================================
-** function to test the API with C. It interprets a kind of assembler
-** language with calls to the API, so the test can be driven by Lua code
-** =====================================================================
-*/
-
-
-static void sethookaux (lua_State *L, int mask, int count, const char *code);
-
-static const char *const delimits = " \t\n,;";
-
-static void skip (const char **pc) {
- for (;;) {
- if (**pc != '\0' && strchr(delimits, **pc)) (*pc)++;
- else if (**pc == '#') { /* comment? */
- while (**pc != '\n' && **pc != '\0') (*pc)++; /* until end-of-line */
- }
- else break;
- }
-}
-
-static int getnum_aux (lua_State *L, lua_State *L1, const char **pc) {
- int res = 0;
- int sig = 1;
- skip(pc);
- if (**pc == '.') {
- res = cast_int(lua_tointeger(L1, -1));
- lua_pop(L1, 1);
- (*pc)++;
- return res;
- }
- else if (**pc == '*') {
- res = lua_gettop(L1);
- (*pc)++;
- return res;
- }
- else if (**pc == '!') {
- (*pc)++;
- if (**pc == 'G')
- res = LUA_RIDX_GLOBALS;
- else if (**pc == 'M')
- res = LUA_RIDX_MAINTHREAD;
- else lua_assert(0);
- (*pc)++;
- return res;
- }
- else if (**pc == '-') {
- sig = -1;
- (*pc)++;
- }
- if (!lisdigit(cast_uchar(**pc)))
- luaL_error(L, "number expected (%s)", *pc);
- while (lisdigit(cast_uchar(**pc))) res = res*10 + (*(*pc)++) - '0';
- return sig*res;
-}
-
-static const char *getstring_aux (lua_State *L, char *buff, const char **pc) {
- int i = 0;
- skip(pc);
- if (**pc == '"' || **pc == '\'') { /* quoted string? */
- int quote = *(*pc)++;
- while (**pc != quote) {
- if (**pc == '\0') luaL_error(L, "unfinished string in C script");
- buff[i++] = *(*pc)++;
- }
- (*pc)++;
- }
- else {
- while (**pc != '\0' && !strchr(delimits, **pc))
- buff[i++] = *(*pc)++;
- }
- buff[i] = '\0';
- return buff;
-}
-
-
-static int getindex_aux (lua_State *L, lua_State *L1, const char **pc) {
- skip(pc);
- switch (*(*pc)++) {
- case 'R': return LUA_REGISTRYINDEX;
- case 'U': return lua_upvalueindex(getnum_aux(L, L1, pc));
- default: {
- int n;
- (*pc)--; /* to read again */
- n = getnum_aux(L, L1, pc);
- if (n == 0) return 0;
- else return lua_absindex(L1, n);
- }
- }
-}
-
-
-static const char *const statcodes[] = {"OK", "YIELD", "ERRRUN",
- "ERRSYNTAX", MEMERRMSG, "ERRERR"};
-
-/*
-** Avoid these stat codes from being collected, to avoid possible
-** memory error when pushing them.
-*/
-static void regcodes (lua_State *L) {
- unsigned int i;
- for (i = 0; i < sizeof(statcodes) / sizeof(statcodes[0]); i++) {
- lua_pushboolean(L, 1);
- lua_setfield(L, LUA_REGISTRYINDEX, statcodes[i]);
- }
-}
-
-
-#define EQ(s1) (strcmp(s1, inst) == 0)
-
-#define getnum (getnum_aux(L, L1, &pc))
-#define getstring (getstring_aux(L, buff, &pc))
-#define getindex (getindex_aux(L, L1, &pc))
-
-
-static int testC (lua_State *L);
-static int Cfunck (lua_State *L, int status, lua_KContext ctx);
-
-/*
-** arithmetic operation encoding for 'arith' instruction
-** LUA_OPIDIV -> \
-** LUA_OPSHL -> <
-** LUA_OPSHR -> >
-** LUA_OPUNM -> _
-** LUA_OPBNOT -> !
-*/
-static const char ops[] = "+-*%^/\\&|~<>_!";
-
-static int runC (lua_State *L, lua_State *L1, const char *pc) {
- char buff[300];
- int status = 0;
- if (pc == NULL) return luaL_error(L, "attempt to runC null script");
- for (;;) {
- const char *inst = getstring;
- if EQ("") return 0;
- else if EQ("absindex") {
- lua_pushinteger(L1, getindex);
- }
- else if EQ("append") {
- int t = getindex;
- int i = cast_int(lua_rawlen(L1, t));
- lua_rawseti(L1, t, i + 1);
- }
- else if EQ("arith") {
- int op;
- skip(&pc);
- op = cast_int(strchr(ops, *pc++) - ops);
- lua_arith(L1, op);
- }
- else if EQ("call") {
- int narg = getnum;
- int nres = getnum;
- lua_call(L1, narg, nres);
- }
- else if EQ("callk") {
- int narg = getnum;
- int nres = getnum;
- int i = getindex;
- lua_callk(L1, narg, nres, i, Cfunck);
- }
- else if EQ("checkstack") {
- int sz = getnum;
- const char *msg = getstring;
- if (*msg == '\0')
- msg = NULL; /* to test 'luaL_checkstack' with no message */
- luaL_checkstack(L1, sz, msg);
- }
- else if EQ("rawcheckstack") {
- int sz = getnum;
- lua_pushboolean(L1, lua_checkstack(L1, sz));
- }
- else if EQ("compare") {
- const char *opt = getstring; /* EQ, LT, or LE */
- int op = (opt[0] == 'E') ? LUA_OPEQ
- : (opt[1] == 'T') ? LUA_OPLT : LUA_OPLE;
- int a = getindex;
- int b = getindex;
- lua_pushboolean(L1, lua_compare(L1, a, b, op));
- }
- else if EQ("concat") {
- lua_concat(L1, getnum);
- }
- else if EQ("copy") {
- int f = getindex;
- lua_copy(L1, f, getindex);
- }
- else if EQ("func2num") {
- lua_CFunction func = lua_tocfunction(L1, getindex);
- lua_pushinteger(L1, cast_st2S(cast_sizet(func)));
- }
- else if EQ("getfield") {
- int t = getindex;
- int tp = lua_getfield(L1, t, getstring);
- lua_assert(tp == lua_type(L1, -1));
- }
- else if EQ("getglobal") {
- lua_getglobal(L1, getstring);
- }
- else if EQ("getmetatable") {
- if (lua_getmetatable(L1, getindex) == 0)
- lua_pushnil(L1);
- }
- else if EQ("gettable") {
- int tp = lua_gettable(L1, getindex);
- lua_assert(tp == lua_type(L1, -1));
- }
- else if EQ("gettop") {
- lua_pushinteger(L1, lua_gettop(L1));
- }
- else if EQ("gsub") {
- int a = getnum; int b = getnum; int c = getnum;
- luaL_gsub(L1, lua_tostring(L1, a),
- lua_tostring(L1, b),
- lua_tostring(L1, c));
- }
- else if EQ("insert") {
- lua_insert(L1, getnum);
- }
- else if EQ("iscfunction") {
- lua_pushboolean(L1, lua_iscfunction(L1, getindex));
- }
- else if EQ("isfunction") {
- lua_pushboolean(L1, lua_isfunction(L1, getindex));
- }
- else if EQ("isnil") {
- lua_pushboolean(L1, lua_isnil(L1, getindex));
- }
- else if EQ("isnull") {
- lua_pushboolean(L1, lua_isnone(L1, getindex));
- }
- else if EQ("isnumber") {
- lua_pushboolean(L1, lua_isnumber(L1, getindex));
- }
- else if EQ("isstring") {
- lua_pushboolean(L1, lua_isstring(L1, getindex));
- }
- else if EQ("istable") {
- lua_pushboolean(L1, lua_istable(L1, getindex));
- }
- else if EQ("isudataval") {
- lua_pushboolean(L1, lua_islightuserdata(L1, getindex));
- }
- else if EQ("isuserdata") {
- lua_pushboolean(L1, lua_isuserdata(L1, getindex));
- }
- else if EQ("len") {
- lua_len(L1, getindex);
- }
- else if EQ("Llen") {
- lua_pushinteger(L1, luaL_len(L1, getindex));
- }
- else if EQ("loadfile") {
- luaL_loadfile(L1, luaL_checkstring(L1, getnum));
- }
- else if EQ("loadstring") {
- size_t slen;
- const char *s = luaL_checklstring(L1, getnum, &slen);
- const char *name = getstring;
- const char *mode = getstring;
- luaL_loadbufferx(L1, s, slen, name, mode);
- }
- else if EQ("newmetatable") {
- lua_pushboolean(L1, luaL_newmetatable(L1, getstring));
- }
- else if EQ("newtable") {
- lua_newtable(L1);
- }
- else if EQ("newthread") {
- lua_newthread(L1);
- }
- else if EQ("resetthread") {
- lua_pushinteger(L1, lua_resetthread(L1)); /* deprecated */
- }
- else if EQ("newuserdata") {
- lua_newuserdata(L1, cast_sizet(getnum));
- }
- else if EQ("next") {
- lua_next(L1, -2);
- }
- else if EQ("objsize") {
- lua_pushinteger(L1, l_castU2S(lua_rawlen(L1, getindex)));
- }
- else if EQ("pcall") {
- int narg = getnum;
- int nres = getnum;
- status = lua_pcall(L1, narg, nres, getnum);
- }
- else if EQ("pcallk") {
- int narg = getnum;
- int nres = getnum;
- int i = getindex;
- status = lua_pcallk(L1, narg, nres, 0, i, Cfunck);
- }
- else if EQ("pop") {
- lua_pop(L1, getnum);
- }
- else if EQ("printstack") {
- int n = getnum;
- if (n != 0) {
- lua_printvalue(s2v(L->ci->func.p + n));
- printf("\n");
- }
- else lua_printstack(L1);
- }
- else if EQ("print") {
- const char *msg = getstring;
- printf("%s\n", msg);
- }
- else if EQ("warningC") {
- const char *msg = getstring;
- lua_warning(L1, msg, 1);
- }
- else if EQ("warning") {
- const char *msg = getstring;
- lua_warning(L1, msg, 0);
- }
- else if EQ("pushbool") {
- lua_pushboolean(L1, getnum);
- }
- else if EQ("pushcclosure") {
- lua_pushcclosure(L1, testC, getnum);
- }
- else if EQ("pushint") {
- lua_pushinteger(L1, getnum);
- }
- else if EQ("pushnil") {
- lua_pushnil(L1);
- }
- else if EQ("pushnum") {
- lua_pushnumber(L1, (lua_Number)getnum);
- }
- else if EQ("pushstatus") {
- lua_pushstring(L1, statcodes[status]);
- }
- else if EQ("pushstring") {
- lua_pushstring(L1, getstring);
- }
- else if EQ("pushupvalueindex") {
- lua_pushinteger(L1, lua_upvalueindex(getnum));
- }
- else if EQ("pushvalue") {
- lua_pushvalue(L1, getindex);
- }
- else if EQ("pushfstringI") {
- lua_pushfstring(L1, lua_tostring(L, -2), (int)lua_tointeger(L, -1));
- }
- else if EQ("pushfstringS") {
- lua_pushfstring(L1, lua_tostring(L, -2), lua_tostring(L, -1));
- }
- else if EQ("pushfstringP") {
- lua_pushfstring(L1, lua_tostring(L, -2), lua_topointer(L, -1));
- }
- else if EQ("rawget") {
- int t = getindex;
- lua_rawget(L1, t);
- }
- else if EQ("rawgeti") {
- int t = getindex;
- lua_rawgeti(L1, t, getnum);
- }
- else if EQ("rawgetp") {
- int t = getindex;
- lua_rawgetp(L1, t, cast_voidp(cast_sizet(getnum)));
- }
- else if EQ("rawset") {
- int t = getindex;
- lua_rawset(L1, t);
- }
- else if EQ("rawseti") {
- int t = getindex;
- lua_rawseti(L1, t, getnum);
- }
- else if EQ("rawsetp") {
- int t = getindex;
- lua_rawsetp(L1, t, cast_voidp(cast_sizet(getnum)));
- }
- else if EQ("remove") {
- lua_remove(L1, getnum);
- }
- else if EQ("replace") {
- lua_replace(L1, getindex);
- }
- else if EQ("resume") {
- int i = getindex;
- int nres;
- status = lua_resume(lua_tothread(L1, i), L, getnum, &nres);
- }
- else if EQ("traceback") {
- const char *msg = getstring;
- int level = getnum;
- luaL_traceback(L1, L1, msg, level);
- }
- else if EQ("threadstatus") {
- lua_pushstring(L1, statcodes[lua_status(L1)]);
- }
- else if EQ("alloccount") {
- l_memcontrol.countlimit = cast_uint(getnum);
- }
- else if EQ("return") {
- int n = getnum;
- if (L1 != L) {
- int i;
- for (i = 0; i < n; i++) {
- int idx = -(n - i);
- switch (lua_type(L1, idx)) {
- case LUA_TBOOLEAN:
- lua_pushboolean(L, lua_toboolean(L1, idx));
- break;
- default:
- lua_pushstring(L, lua_tostring(L1, idx));
- break;
- }
- }
- }
- return n;
- }
- else if EQ("rotate") {
- int i = getindex;
- lua_rotate(L1, i, getnum);
- }
- else if EQ("setfield") {
- int t = getindex;
- const char *s = getstring;
- lua_setfield(L1, t, s);
- }
- else if EQ("seti") {
- int t = getindex;
- lua_seti(L1, t, getnum);
- }
- else if EQ("setglobal") {
- const char *s = getstring;
- lua_setglobal(L1, s);
- }
- else if EQ("sethook") {
- int mask = getnum;
- int count = getnum;
- const char *s = getstring;
- sethookaux(L1, mask, count, s);
- }
- else if EQ("setmetatable") {
- int idx = getindex;
- lua_setmetatable(L1, idx);
- }
- else if EQ("settable") {
- lua_settable(L1, getindex);
- }
- else if EQ("settop") {
- lua_settop(L1, getnum);
- }
- else if EQ("testudata") {
- int i = getindex;
- lua_pushboolean(L1, luaL_testudata(L1, i, getstring) != NULL);
- }
- else if EQ("error") {
- lua_error(L1);
- }
- else if EQ("abort") {
- abort();
- }
- else if EQ("throw") {
-#if defined(__cplusplus)
-static struct X { int x; } x;
- throw x;
-#else
- luaL_error(L1, "C++");
-#endif
- break;
- }
- else if EQ("tobool") {
- lua_pushboolean(L1, lua_toboolean(L1, getindex));
- }
- else if EQ("tocfunction") {
- lua_pushcfunction(L1, lua_tocfunction(L1, getindex));
- }
- else if EQ("tointeger") {
- lua_pushinteger(L1, lua_tointeger(L1, getindex));
- }
- else if EQ("tonumber") {
- lua_pushnumber(L1, lua_tonumber(L1, getindex));
- }
- else if EQ("topointer") {
- lua_pushlightuserdata(L1, cast_voidp(lua_topointer(L1, getindex)));
- }
- else if EQ("touserdata") {
- lua_pushlightuserdata(L1, lua_touserdata(L1, getindex));
- }
- else if EQ("tostring") {
- const char *s = lua_tostring(L1, getindex);
- const char *s1 = lua_pushstring(L1, s);
- cast_void(s1); /* to avoid warnings */
- lua_longassert((s == NULL && s1 == NULL) || strcmp(s, s1) == 0);
- }
- else if EQ("Ltolstring") {
- luaL_tolstring(L1, getindex, NULL);
- }
- else if EQ("type") {
- lua_pushstring(L1, luaL_typename(L1, getnum));
- }
- else if EQ("xmove") {
- int f = getindex;
- int t = getindex;
- lua_State *fs = (f == 0) ? L1 : lua_tothread(L1, f);
- lua_State *ts = (t == 0) ? L1 : lua_tothread(L1, t);
- int n = getnum;
- if (n == 0) n = lua_gettop(fs);
- lua_xmove(fs, ts, n);
- }
- else if EQ("isyieldable") {
- lua_pushboolean(L1, lua_isyieldable(lua_tothread(L1, getindex)));
- }
- else if EQ("yield") {
- return lua_yield(L1, getnum);
- }
- else if EQ("yieldk") {
- int nres = getnum;
- int i = getindex;
- return lua_yieldk(L1, nres, i, Cfunck);
- }
- else if EQ("toclose") {
- lua_toclose(L1, getnum);
- }
- else if EQ("closeslot") {
- lua_closeslot(L1, getnum);
- }
- else if EQ("argerror") {
- int arg = getnum;
- luaL_argerror(L1, arg, getstring);
- }
- else luaL_error(L, "unknown instruction %s", buff);
- }
- return 0;
-}
-
-
-static int testC (lua_State *L) {
- lua_State *L1;
- const char *pc;
- if (lua_isuserdata(L, 1)) {
- L1 = getstate(L);
- pc = luaL_checkstring(L, 2);
- }
- else if (lua_isthread(L, 1)) {
- L1 = lua_tothread(L, 1);
- pc = luaL_checkstring(L, 2);
- }
- else {
- L1 = L;
- pc = luaL_checkstring(L, 1);
- }
- return runC(L, L1, pc);
-}
-
-
-static int Cfunc (lua_State *L) {
- return runC(L, L, lua_tostring(L, lua_upvalueindex(1)));
-}
-
-
-static int Cfunck (lua_State *L, int status, lua_KContext ctx) {
- lua_pushstring(L, statcodes[status]);
- lua_setglobal(L, "status");
- lua_pushinteger(L, cast_Integer(ctx));
- lua_setglobal(L, "ctx");
- return runC(L, L, lua_tostring(L, cast_int(ctx)));
-}
-
-
-static int makeCfunc (lua_State *L) {
- luaL_checkstring(L, 1);
- lua_pushcclosure(L, Cfunc, lua_gettop(L));
- return 1;
-}
-
-
-/* }====================================================== */
-
-
-/*
-** {======================================================
-** tests for C hooks
-** =======================================================
-*/
-
-/*
-** C hook that runs the C script stored in registry.C_HOOK[L]
-*/
-static void Chook (lua_State *L, lua_Debug *ar) {
- const char *scpt;
- const char *const events [] = {"call", "ret", "line", "count", "tailcall"};
- lua_getfield(L, LUA_REGISTRYINDEX, "C_HOOK");
- lua_pushlightuserdata(L, L);
- lua_gettable(L, -2); /* get C_HOOK[L] (script saved by sethookaux) */
- scpt = lua_tostring(L, -1); /* not very religious (string will be popped) */
- lua_pop(L, 2); /* remove C_HOOK and script */
- lua_pushstring(L, events[ar->event]); /* may be used by script */
- lua_pushinteger(L, ar->currentline); /* may be used by script */
- runC(L, L, scpt); /* run script from C_HOOK[L] */
-}
-
-
-/*
-** sets 'registry.C_HOOK[L] = scpt' and sets 'Chook' as a hook
-*/
-static void sethookaux (lua_State *L, int mask, int count, const char *scpt) {
- if (*scpt == '\0') { /* no script? */
- lua_sethook(L, NULL, 0, 0); /* turn off hooks */
- return;
- }
- lua_getfield(L, LUA_REGISTRYINDEX, "C_HOOK"); /* get C_HOOK table */
- if (!lua_istable(L, -1)) { /* no hook table? */
- lua_pop(L, 1); /* remove previous value */
- lua_newtable(L); /* create new C_HOOK table */
- lua_pushvalue(L, -1);
- lua_setfield(L, LUA_REGISTRYINDEX, "C_HOOK"); /* register it */
- }
- lua_pushlightuserdata(L, L);
- lua_pushstring(L, scpt);
- lua_settable(L, -3); /* C_HOOK[L] = script */
- lua_sethook(L, Chook, mask, count);
-}
-
-
-static int sethook (lua_State *L) {
- if (lua_isnoneornil(L, 1))
- lua_sethook(L, NULL, 0, 0); /* turn off hooks */
- else {
- const char *scpt = luaL_checkstring(L, 1);
- const char *smask = luaL_checkstring(L, 2);
- int count = cast_int(luaL_optinteger(L, 3, 0));
- int mask = 0;
- if (strchr(smask, 'c')) mask |= LUA_MASKCALL;
- if (strchr(smask, 'r')) mask |= LUA_MASKRET;
- if (strchr(smask, 'l')) mask |= LUA_MASKLINE;
- if (count > 0) mask |= LUA_MASKCOUNT;
- sethookaux(L, mask, count, scpt);
- }
- return 0;
-}
-
-
-static int coresume (lua_State *L) {
- int status, nres;
- lua_State *co = lua_tothread(L, 1);
- luaL_argcheck(L, co, 1, "coroutine expected");
- status = lua_resume(co, L, 0, &nres);
- if (status != LUA_OK && status != LUA_YIELD) {
- lua_pushboolean(L, 0);
- lua_insert(L, -2);
- return 2; /* return false + error message */
- }
- else {
- lua_pushboolean(L, 1);
- return 1;
- }
-}
-
-#if !defined(LUA_USE_POSIX)
-
-#define nonblock NULL
-
-#else
-
-#include
-#include
-
-static int nonblock (lua_State *L) {
- FILE *f = cast(luaL_Stream*, luaL_checkudata(L, 1, LUA_FILEHANDLE))->f;
- int fd = fileno(f);
- int flags = fcntl(fd, F_GETFL, 0);
- flags |= O_NONBLOCK;
- fcntl(fd, F_SETFL, flags);
- return 0;
-}
-#endif
-
-/* }====================================================== */
-
-
-
-static const struct luaL_Reg tests_funcs[] = {
- {"checkmemory", lua_checkmemory},
- {"closestate", closestate},
- {"d2s", d2s},
- {"doonnewstack", doonnewstack},
- {"doremote", doremote},
- {"gccolor", gc_color},
- {"gcage", gc_age},
- {"gcstate", gc_state},
- {"tracegc", tracegc},
- {"pobj", gc_printobj},
- {"getref", getref},
- {"hash", hash_query},
- {"log2", log2_aux},
- {"limits", get_limits},
- {"listcode", listcode},
- {"printcode", printcode},
- {"printallstack", lua_printallstack},
- {"listk", listk},
- {"listabslineinfo", listabslineinfo},
- {"listlocals", listlocals},
- {"loadlib", loadlib},
- {"checkpanic", checkpanic},
- {"newstate", newstate},
- {"newuserdata", newuserdata},
- {"num2int", num2int},
- {"makeseed", makeseed},
- {"pushuserdata", pushuserdata},
- {"gcquery", gc_query},
- {"querystr", string_query},
- {"querytab", table_query},
- {"codeparam", test_codeparam},
- {"applyparam", test_applyparam},
- {"ref", tref},
- {"resume", coresume},
- {"s2d", s2d},
- {"sethook", sethook},
- {"stacklevel", stacklevel},
- {"resetCI", resetCI},
- {"reallocstack", reallocstack},
- {"sizes", get_sizes},
- {"testC", testC},
- {"makeCfunc", makeCfunc},
- {"totalmem", mem_query},
- {"alloccount", alloc_count},
- {"allocfailnext", alloc_failnext},
- {"trick", settrick},
- {"udataval", udataval},
- {"unref", unref},
- {"upvalue", upvalue},
- {"externKstr", externKstr},
- {"externstr", externstr},
- {"nonblock", nonblock},
- {NULL, NULL}
-};
-
-
-static void checkfinalmem (void) {
- lua_assert(l_memcontrol.numblocks == 0);
- lua_assert(l_memcontrol.total == 0);
-}
-
-
-int luaB_opentests (lua_State *L) {
- void *ud;
- lua_Alloc f = lua_getallocf(L, &ud);
- lua_atpanic(L, &tpanic);
- lua_setwarnf(L, &warnf, L);
- lua_pushboolean(L, 0);
- lua_setglobal(L, "_WARN"); /* _WARN = false */
- regcodes(L);
- atexit(checkfinalmem);
- lua_assert(f == debug_realloc && ud == cast_voidp(&l_memcontrol));
- lua_setallocf(L, f, ud); /* exercise this function */
- luaL_newlib(L, tests_funcs);
- return 1;
-}
-
-#endif
-
diff --git a/ltests.h b/ltests.h
deleted file mode 100644
index f5f14cd61c..0000000000
--- a/ltests.h
+++ /dev/null
@@ -1,167 +0,0 @@
-/*
-** $Id: ltests.h $
-** Internal Header for Debugging of the Lua Implementation
-** See Copyright Notice in lua.h
-*/
-
-#ifndef ltests_h
-#define ltests_h
-
-
-#include
-#include
-
-/* test Lua with compatibility code */
-#define LUA_COMPAT_MATHLIB
-#undef LUA_COMPAT_GLOBAL
-#define LUA_COMPAT_GLOBAL 0
-
-
-#define LUA_DEBUG
-
-
-/* turn on assertions */
-#define LUAI_ASSERT
-
-
-/* to avoid warnings, and to make sure value is really unused */
-#define UNUSED(x) (x=0, (void)(x))
-
-
-/* test for sizes in 'l_sprintf' (make sure whole buffer is available) */
-#undef l_sprintf
-#if !defined(LUA_USE_C89)
-#define l_sprintf(s,sz,f,i) (memset(s,0xAB,sz), snprintf(s,sz,f,i))
-#else
-#define l_sprintf(s,sz,f,i) (memset(s,0xAB,sz), sprintf(s,f,i))
-#endif
-
-
-/* get a chance to test code without jump tables */
-#define LUA_USE_JUMPTABLE 0
-
-
-/* use 32-bit integers in random generator */
-#define LUA_RAND32
-
-
-/* test stack reallocation without strict address use */
-#define LUAI_STRICT_ADDRESS 0
-
-
-/* memory-allocator control variables */
-typedef struct Memcontrol {
- int failnext;
- unsigned long numblocks;
- unsigned long total;
- unsigned long maxmem;
- unsigned long memlimit;
- unsigned long countlimit;
- unsigned long objcount[LUA_NUMTYPES];
-} Memcontrol;
-
-LUA_API Memcontrol l_memcontrol;
-
-
-#define luai_tracegc(L,f) luai_tracegctest(L, f)
-extern void luai_tracegctest (lua_State *L, int first);
-
-
-/*
-** generic variable for debug tricks
-*/
-extern void *l_Trick;
-
-
-/*
-** Function to traverse and check all memory used by Lua
-*/
-extern int lua_checkmemory (lua_State *L);
-
-/*
-** Function to print an object GC-friendly
-*/
-struct GCObject;
-extern void lua_printobj (lua_State *L, struct GCObject *o);
-
-
-/*
-** Function to print a value
-*/
-struct TValue;
-extern void lua_printvalue (struct TValue *v);
-
-/*
-** Function to print the stack
-*/
-extern void lua_printstack (lua_State *L);
-extern int lua_printallstack (lua_State *L);
-
-
-/* test for lock/unlock */
-
-struct L_EXTRA { int lock; int *plock; };
-#undef LUA_EXTRASPACE
-#define LUA_EXTRASPACE sizeof(struct L_EXTRA)
-#define getlock(l) cast(struct L_EXTRA*, lua_getextraspace(l))
-#define luai_userstateopen(l) \
- (getlock(l)->lock = 0, getlock(l)->plock = &(getlock(l)->lock))
-#define luai_userstateclose(l) \
- lua_assert(getlock(l)->lock == 1 && getlock(l)->plock == &(getlock(l)->lock))
-#define luai_userstatethread(l,l1) \
- lua_assert(getlock(l1)->plock == getlock(l)->plock)
-#define luai_userstatefree(l,l1) \
- lua_assert(getlock(l)->plock == getlock(l1)->plock)
-#define lua_lock(l) lua_assert((*getlock(l)->plock)++ == 0)
-#define lua_unlock(l) lua_assert(--(*getlock(l)->plock) == 0)
-
-
-
-LUA_API int luaB_opentests (lua_State *L);
-
-LUA_API void *debug_realloc (void *ud, void *block,
- size_t osize, size_t nsize);
-
-
-#define luaL_newstate() \
- lua_newstate(debug_realloc, &l_memcontrol, luaL_makeseed(NULL))
-#define luai_openlibs(L) \
- { luaL_openlibs(L); \
- luaL_requiref(L, "T", luaB_opentests, 1); \
- lua_pop(L, 1); }
-
-
-
-
-/* change some sizes to give some bugs a chance */
-
-#undef LUAL_BUFFERSIZE
-#define LUAL_BUFFERSIZE 23
-#define MINSTRTABSIZE 2
-#define MAXIWTHABS 3
-
-#define STRCACHE_N 23
-#define STRCACHE_M 5
-
-#define MAXINDEXRK 1
-
-
-/*
-** Reduce maximum stack size to make stack-overflow tests run faster.
-** (But value is still large enough to overflow smaller integers.)
-*/
-#define LUAI_MAXSTACK 68000
-
-
-/* test mode uses more stack space */
-#undef LUAI_MAXCCALLS
-#define LUAI_MAXCCALLS 180
-
-
-/* force Lua to use its own implementations */
-#undef lua_strx2number
-#undef lua_number2strx
-
-
-#endif
-
diff --git a/ltm.c b/ltm.c
deleted file mode 100644
index f2a373f86c..0000000000
--- a/ltm.c
+++ /dev/null
@@ -1,364 +0,0 @@
-/*
-** $Id: ltm.c $
-** Tag methods
-** See Copyright Notice in lua.h
-*/
-
-#define ltm_c
-#define LUA_CORE
-
-#include "lprefix.h"
-
-
-#include
-
-#include "lua.h"
-
-#include "ldebug.h"
-#include "ldo.h"
-#include "lgc.h"
-#include "lobject.h"
-#include "lstate.h"
-#include "lstring.h"
-#include "ltable.h"
-#include "ltm.h"
-#include "lvm.h"
-
-
-static const char udatatypename[] = "userdata";
-
-LUAI_DDEF const char *const luaT_typenames_[LUA_TOTALTYPES] = {
- "no value",
- "nil", "boolean", udatatypename, "number",
- "string", "table", "function", udatatypename, "thread",
- "upvalue", "proto" /* these last cases are used for tests only */
-};
-
-
-void luaT_init (lua_State *L) {
- static const char *const luaT_eventname[] = { /* ORDER TM */
- "__index", "__newindex",
- "__gc", "__mode", "__len", "__eq",
- "__add", "__sub", "__mul", "__mod", "__pow",
- "__div", "__idiv",
- "__band", "__bor", "__bxor", "__shl", "__shr",
- "__unm", "__bnot", "__lt", "__le",
- "__concat", "__call", "__close"
- };
- int i;
- for (i=0; itmname[i] = luaS_new(L, luaT_eventname[i]);
- luaC_fix(L, obj2gco(G(L)->tmname[i])); /* never collect these names */
- }
-}
-
-
-/*
-** function to be used with macro "fasttm": optimized for absence of
-** tag methods
-*/
-const TValue *luaT_gettm (Table *events, TMS event, TString *ename) {
- const TValue *tm = luaH_Hgetshortstr(events, ename);
- lua_assert(event <= TM_EQ);
- if (notm(tm)) { /* no tag method? */
- events->flags |= cast_byte(1u<metatable;
- break;
- case LUA_TUSERDATA:
- mt = uvalue(o)->metatable;
- break;
- default:
- mt = G(L)->mt[ttype(o)];
- }
- return (mt ? luaH_Hgetshortstr(mt, G(L)->tmname[event]) : &G(L)->nilvalue);
-}
-
-
-/*
-** Return the name of the type of an object. For tables and userdata
-** with metatable, use their '__name' metafield, if present.
-*/
-const char *luaT_objtypename (lua_State *L, const TValue *o) {
- Table *mt;
- if ((ttistable(o) && (mt = hvalue(o)->metatable) != NULL) ||
- (ttisfulluserdata(o) && (mt = uvalue(o)->metatable) != NULL)) {
- const TValue *name = luaH_Hgetshortstr(mt, luaS_new(L, "__name"));
- if (ttisstring(name)) /* is '__name' a string? */
- return getstr(tsvalue(name)); /* use it as type name */
- }
- return ttypename(ttype(o)); /* else use standard type name */
-}
-
-
-void luaT_callTM (lua_State *L, const TValue *f, const TValue *p1,
- const TValue *p2, const TValue *p3) {
- StkId func = L->top.p;
- setobj2s(L, func, f); /* push function (assume EXTRA_STACK) */
- setobj2s(L, func + 1, p1); /* 1st argument */
- setobj2s(L, func + 2, p2); /* 2nd argument */
- setobj2s(L, func + 3, p3); /* 3rd argument */
- L->top.p = func + 4;
- /* metamethod may yield only when called from Lua code */
- if (isLuacode(L->ci))
- luaD_call(L, func, 0);
- else
- luaD_callnoyield(L, func, 0);
-}
-
-
-lu_byte luaT_callTMres (lua_State *L, const TValue *f, const TValue *p1,
- const TValue *p2, StkId res) {
- ptrdiff_t result = savestack(L, res);
- StkId func = L->top.p;
- setobj2s(L, func, f); /* push function (assume EXTRA_STACK) */
- setobj2s(L, func + 1, p1); /* 1st argument */
- setobj2s(L, func + 2, p2); /* 2nd argument */
- L->top.p += 3;
- /* metamethod may yield only when called from Lua code */
- if (isLuacode(L->ci))
- luaD_call(L, func, 1);
- else
- luaD_callnoyield(L, func, 1);
- res = restorestack(L, result);
- setobjs2s(L, res, --L->top.p); /* move result to its place */
- return ttypetag(s2v(res)); /* return tag of the result */
-}
-
-
-static int callbinTM (lua_State *L, const TValue *p1, const TValue *p2,
- StkId res, TMS event) {
- const TValue *tm = luaT_gettmbyobj(L, p1, event); /* try first operand */
- if (notm(tm))
- tm = luaT_gettmbyobj(L, p2, event); /* try second operand */
- if (notm(tm))
- return -1; /* tag method not found */
- else /* call tag method and return the tag of the result */
- return luaT_callTMres(L, tm, p1, p2, res);
-}
-
-
-void luaT_trybinTM (lua_State *L, const TValue *p1, const TValue *p2,
- StkId res, TMS event) {
- if (l_unlikely(callbinTM(L, p1, p2, res, event) < 0)) {
- switch (event) {
- case TM_BAND: case TM_BOR: case TM_BXOR:
- case TM_SHL: case TM_SHR: case TM_BNOT: {
- if (ttisnumber(p1) && ttisnumber(p2))
- luaG_tointerror(L, p1, p2);
- else
- luaG_opinterror(L, p1, p2, "perform bitwise operation on");
- }
- /* calls never return, but to avoid warnings: *//* FALLTHROUGH */
- default:
- luaG_opinterror(L, p1, p2, "perform arithmetic on");
- }
- }
-}
-
-
-/*
-** The use of 'p1' after 'callbinTM' is safe because, when a tag
-** method is not found, 'callbinTM' cannot change the stack.
-*/
-void luaT_tryconcatTM (lua_State *L) {
- StkId p1 = L->top.p - 2; /* first argument */
- if (l_unlikely(callbinTM(L, s2v(p1), s2v(p1 + 1), p1, TM_CONCAT) < 0))
- luaG_concaterror(L, s2v(p1), s2v(p1 + 1));
-}
-
-
-void luaT_trybinassocTM (lua_State *L, const TValue *p1, const TValue *p2,
- int flip, StkId res, TMS event) {
- if (flip)
- luaT_trybinTM(L, p2, p1, res, event);
- else
- luaT_trybinTM(L, p1, p2, res, event);
-}
-
-
-void luaT_trybiniTM (lua_State *L, const TValue *p1, lua_Integer i2,
- int flip, StkId res, TMS event) {
- TValue aux;
- setivalue(&aux, i2);
- luaT_trybinassocTM(L, p1, &aux, flip, res, event);
-}
-
-
-/*
-** Calls an order tag method.
-*/
-int luaT_callorderTM (lua_State *L, const TValue *p1, const TValue *p2,
- TMS event) {
- int tag = callbinTM(L, p1, p2, L->top.p, event); /* try original event */
- if (tag >= 0) /* found tag method? */
- return !tagisfalse(tag);
- luaG_ordererror(L, p1, p2); /* no metamethod found */
- return 0; /* to avoid warnings */
-}
-
-
-int luaT_callorderiTM (lua_State *L, const TValue *p1, int v2,
- int flip, int isfloat, TMS event) {
- TValue aux; const TValue *p2;
- if (isfloat) {
- setfltvalue(&aux, cast_num(v2));
- }
- else
- setivalue(&aux, v2);
- if (flip) { /* arguments were exchanged? */
- p2 = p1; p1 = &aux; /* correct them */
- }
- else
- p2 = &aux;
- return luaT_callorderTM(L, p1, p2, event);
-}
-
-
-/*
-** Create a vararg table at the top of the stack, with 'n' elements
-** starting at 'f'.
-*/
-static void createvarargtab (lua_State *L, StkId f, int n) {
- int i;
- TValue key, value;
- Table *t = luaH_new(L);
- sethvalue(L, s2v(L->top.p), t);
- L->top.p++;
- luaH_resize(L, t, cast_uint(n), 1);
- setsvalue(L, &key, luaS_new(L, "n")); /* key is "n" */
- setivalue(&value, n); /* value is n */
- /* No need to anchor the key: Due to the resize, the next operation
- cannot trigger a garbage collection */
- luaH_set(L, t, &key, &value); /* t.n = n */
- for (i = 0; i < n; i++)
- luaH_setint(L, t, i + 1, s2v(f + i));
- luaC_checkGC(L);
-}
-
-
-/*
-** initial stack: func arg1 ... argn extra1 ...
-** ^ ci->func ^ L->top
-** final stack: func nil ... nil extra1 ... func arg1 ... argn
-** ^ ci->func
-*/
-static void buildhiddenargs (lua_State *L, CallInfo *ci, const Proto *p,
- int totalargs, int nfixparams, int nextra) {
- int i;
- ci->u.l.nextraargs = nextra;
- luaD_checkstack(L, p->maxstacksize + 1);
- /* copy function to the top of the stack, after extra arguments */
- setobjs2s(L, L->top.p++, ci->func.p);
- /* move fixed parameters to after the copied function */
- for (i = 1; i <= nfixparams; i++) {
- setobjs2s(L, L->top.p++, ci->func.p + i);
- setnilvalue(s2v(ci->func.p + i)); /* erase original parameter (for GC) */
- }
- ci->func.p += totalargs + 1; /* 'func' now lives after hidden arguments */
- ci->top.p += totalargs + 1;
-}
-
-
-void luaT_adjustvarargs (lua_State *L, CallInfo *ci, const Proto *p) {
- int totalargs = cast_int(L->top.p - ci->func.p) - 1;
- int nfixparams = p->numparams;
- int nextra = totalargs - nfixparams; /* number of extra arguments */
- if (p->flag & PF_VATAB) { /* does it need a vararg table? */
- lua_assert(!(p->flag & PF_VAHID));
- createvarargtab(L, ci->func.p + nfixparams + 1, nextra);
- /* move table to proper place (last parameter) */
- setobjs2s(L, ci->func.p + nfixparams + 1, L->top.p - 1);
- }
- else { /* no table */
- lua_assert(p->flag & PF_VAHID);
- buildhiddenargs(L, ci, p, totalargs, nfixparams, nextra);
- /* set vararg parameter to nil */
- setnilvalue(s2v(ci->func.p + nfixparams + 1));
- lua_assert(L->top.p <= ci->top.p && ci->top.p <= L->stack_last.p);
- }
-}
-
-
-void luaT_getvararg (CallInfo *ci, StkId ra, TValue *rc) {
- int nextra = ci->u.l.nextraargs;
- lua_Integer n;
- if (tointegerns(rc, &n)) { /* integral value? */
- if (l_castS2U(n) - 1 < cast_uint(nextra)) {
- StkId slot = ci->func.p - nextra + cast_int(n) - 1;
- setobjs2s(((lua_State*)NULL), ra, slot);
- return;
- }
- }
- else if (ttisstring(rc)) { /* string value? */
- size_t len;
- const char *s = getlstr(tsvalue(rc), len);
- if (len == 1 && s[0] == 'n') { /* key is "n"? */
- setivalue(s2v(ra), nextra);
- return;
- }
- }
- setnilvalue(s2v(ra)); /* else produce nil */
-}
-
-
-/*
-** Get the number of extra arguments in a vararg function. If vararg
-** table has been optimized away, that number is in the call info.
-** Otherwise, get the field 'n' from the vararg table and check that it
-** has a proper value (non-negative integer not larger than the stack
-** limit).
-*/
-static int getnumargs (lua_State *L, CallInfo *ci, Table *h) {
- if (h == NULL) /* no vararg table? */
- return ci->u.l.nextraargs;
- else {
- TValue res;
- if (luaH_getshortstr(h, luaS_new(L, "n"), &res) != LUA_VNUMINT ||
- l_castS2U(ivalue(&res)) > cast_uint(INT_MAX/2))
- luaG_runerror(L, "vararg table has no proper 'n'");
- return cast_int(ivalue(&res));
- }
-}
-
-
-/*
-** Get 'wanted' vararg arguments and put them in 'where'. 'vatab' is
-** the register of the vararg table or -1 if there is no vararg table.
-*/
-void luaT_getvarargs (lua_State *L, CallInfo *ci, StkId where, int wanted,
- int vatab) {
- Table *h = (vatab < 0) ? NULL : hvalue(s2v(ci->func.p + vatab + 1));
- int nargs = getnumargs(L, ci, h); /* number of available vararg args. */
- int i, touse; /* 'touse' is minimum between 'wanted' and 'nargs' */
- if (wanted < 0) {
- touse = wanted = nargs; /* get all extra arguments available */
- checkstackp(L, nargs, where); /* ensure stack space */
- L->top.p = where + nargs; /* next instruction will need top */
- }
- else
- touse = (nargs > wanted) ? wanted : nargs;
- if (h == NULL) { /* no vararg table? */
- for (i = 0; i < touse; i++) /* get vararg values from the stack */
- setobjs2s(L, where + i, ci->func.p - nargs + i);
- }
- else { /* get vararg values from vararg table */
- for (i = 0; i < touse; i++) {
- lu_byte tag = luaH_getint(h, i + 1, s2v(where + i));
- if (tagisempty(tag))
- setnilvalue(s2v(where + i));
- }
- }
- for (; i < wanted; i++) /* complete required results with nil */
- setnilvalue(s2v(where + i));
-}
-
diff --git a/ltm.h b/ltm.h
deleted file mode 100644
index afc7ad00e2..0000000000
--- a/ltm.h
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
-** $Id: ltm.h $
-** Tag methods
-** See Copyright Notice in lua.h
-*/
-
-#ifndef ltm_h
-#define ltm_h
-
-
-#include "lobject.h"
-
-
-/*
-* WARNING: if you change the order of this enumeration,
-* grep "ORDER TM" and "ORDER OP"
-*/
-typedef enum {
- TM_INDEX,
- TM_NEWINDEX,
- TM_GC,
- TM_MODE,
- TM_LEN,
- TM_EQ, /* last tag method with fast access */
- TM_ADD,
- TM_SUB,
- TM_MUL,
- TM_MOD,
- TM_POW,
- TM_DIV,
- TM_IDIV,
- TM_BAND,
- TM_BOR,
- TM_BXOR,
- TM_SHL,
- TM_SHR,
- TM_UNM,
- TM_BNOT,
- TM_LT,
- TM_LE,
- TM_CONCAT,
- TM_CALL,
- TM_CLOSE,
- TM_N /* number of elements in the enum */
-} TMS;
-
-
-/*
-** Mask with 1 in all fast-access methods. A 1 in any of these bits
-** in the flag of a (meta)table means the metatable does not have the
-** corresponding metamethod field. (Bit 6 of the flag indicates that
-** the table is using the dummy node.)
-*/
-#define maskflags cast_byte(~(~0u << (TM_EQ + 1)))
-
-
-/*
-** Test whether there is no tagmethod.
-** (Because tagmethods use raw accesses, the result may be an "empty" nil.)
-*/
-#define notm(tm) ttisnil(tm)
-
-#define checknoTM(mt,e) ((mt) == NULL || (mt)->flags & (1u<<(e)))
-
-#define gfasttm(g,mt,e) \
- (checknoTM(mt, e) ? NULL : luaT_gettm(mt, e, (g)->tmname[e]))
-
-#define fasttm(l,mt,e) gfasttm(G(l), mt, e)
-
-#define ttypename(x) luaT_typenames_[(x) + 1]
-
-LUAI_DDEC(const char *const luaT_typenames_[LUA_TOTALTYPES];)
-
-
-LUAI_FUNC const char *luaT_objtypename (lua_State *L, const TValue *o);
-
-LUAI_FUNC const TValue *luaT_gettm (Table *events, TMS event, TString *ename);
-LUAI_FUNC const TValue *luaT_gettmbyobj (lua_State *L, const TValue *o,
- TMS event);
-LUAI_FUNC void luaT_init (lua_State *L);
-
-LUAI_FUNC void luaT_callTM (lua_State *L, const TValue *f, const TValue *p1,
- const TValue *p2, const TValue *p3);
-LUAI_FUNC lu_byte luaT_callTMres (lua_State *L, const TValue *f,
- const TValue *p1, const TValue *p2, StkId p3);
-LUAI_FUNC void luaT_trybinTM (lua_State *L, const TValue *p1, const TValue *p2,
- StkId res, TMS event);
-LUAI_FUNC void luaT_tryconcatTM (lua_State *L);
-LUAI_FUNC void luaT_trybinassocTM (lua_State *L, const TValue *p1,
- const TValue *p2, int inv, StkId res, TMS event);
-LUAI_FUNC void luaT_trybiniTM (lua_State *L, const TValue *p1, lua_Integer i2,
- int inv, StkId res, TMS event);
-LUAI_FUNC int luaT_callorderTM (lua_State *L, const TValue *p1,
- const TValue *p2, TMS event);
-LUAI_FUNC int luaT_callorderiTM (lua_State *L, const TValue *p1, int v2,
- int inv, int isfloat, TMS event);
-
-LUAI_FUNC void luaT_adjustvarargs (lua_State *L, struct CallInfo *ci,
- const Proto *p);
-LUAI_FUNC void luaT_getvararg (CallInfo *ci, StkId ra, TValue *rc);
-LUAI_FUNC void luaT_getvarargs (lua_State *L, struct CallInfo *ci, StkId where,
- int wanted, int vatab);
-
-
-#endif
diff --git a/lundump.c b/lundump.c
deleted file mode 100644
index 3b61cc8cbb..0000000000
--- a/lundump.c
+++ /dev/null
@@ -1,424 +0,0 @@
-/*
-** $Id: lundump.c $
-** load precompiled Lua chunks
-** See Copyright Notice in lua.h
-*/
-
-#define lundump_c
-#define LUA_CORE
-
-#include "lprefix.h"
-
-
-#include
-#include
-
-#include "lua.h"
-
-#include "ldebug.h"
-#include "ldo.h"
-#include "lfunc.h"
-#include "lmem.h"
-#include "lobject.h"
-#include "lstring.h"
-#include "ltable.h"
-#include "lundump.h"
-#include "lzio.h"
-
-
-#if !defined(luai_verifycode)
-#define luai_verifycode(L,f) /* empty */
-#endif
-
-
-typedef struct {
- lua_State *L;
- ZIO *Z;
- const char *name;
- Table *h; /* list for string reuse */
- size_t offset; /* current position relative to beginning of dump */
- lua_Unsigned nstr; /* number of strings in the list */
- lu_byte fixed; /* dump is fixed in memory */
-} LoadState;
-
-
-static l_noret error (LoadState *S, const char *why) {
- luaO_pushfstring(S->L, "%s: bad binary format (%s)", S->name, why);
- luaD_throw(S->L, LUA_ERRSYNTAX);
-}
-
-
-/*
-** All high-level loads go through loadVector; you can change it to
-** adapt to the endianness of the input
-*/
-#define loadVector(S,b,n) loadBlock(S,b,cast_sizet(n)*sizeof((b)[0]))
-
-static void loadBlock (LoadState *S, void *b, size_t size) {
- if (luaZ_read(S->Z, b, size) != 0)
- error(S, "truncated chunk");
- S->offset += size;
-}
-
-
-static void loadAlign (LoadState *S, unsigned align) {
- unsigned padding = align - cast_uint(S->offset % align);
- if (padding < align) { /* (padding == align) means no padding */
- lua_Integer paddingContent;
- loadBlock(S, &paddingContent, padding);
- lua_assert(S->offset % align == 0);
- }
-}
-
-
-#define getaddr(S,n,t) cast(t *, getaddr_(S,cast_sizet(n) * sizeof(t)))
-
-static const void *getaddr_ (LoadState *S, size_t size) {
- const void *block = luaZ_getaddr(S->Z, size);
- S->offset += size;
- if (block == NULL)
- error(S, "truncated fixed buffer");
- return block;
-}
-
-
-#define loadVar(S,x) loadVector(S,&x,1)
-
-
-static lu_byte loadByte (LoadState *S) {
- int b = zgetc(S->Z);
- if (b == EOZ)
- error(S, "truncated chunk");
- S->offset++;
- return cast_byte(b);
-}
-
-
-static lua_Unsigned loadVarint (LoadState *S, lua_Unsigned limit) {
- lua_Unsigned x = 0;
- int b;
- limit >>= 7;
- do {
- b = loadByte(S);
- if (x > limit)
- error(S, "integer overflow");
- x = (x << 7) | (b & 0x7f);
- } while ((b & 0x80) != 0);
- return x;
-}
-
-
-static size_t loadSize (LoadState *S) {
- return cast_sizet(loadVarint(S, MAX_SIZE));
-}
-
-
-static int loadInt (LoadState *S) {
- return cast_int(loadVarint(S, cast_sizet(INT_MAX)));
-}
-
-
-
-static lua_Number loadNumber (LoadState *S) {
- lua_Number x;
- loadVar(S, x);
- return x;
-}
-
-
-static lua_Integer loadInteger (LoadState *S) {
- lua_Unsigned cx = loadVarint(S, LUA_MAXUNSIGNED);
- /* decode unsigned to signed */
- if ((cx & 1) != 0)
- return l_castU2S(~(cx >> 1));
- else
- return l_castU2S(cx >> 1);
-}
-
-
-/*
-** Load a nullable string into slot 'sl' from prototype 'p'. The
-** assignment to the slot and the barrier must be performed before any
-** possible GC activity, to anchor the string. (Both 'loadVector' and
-** 'luaH_setint' can call the GC.)
-*/
-static void loadString (LoadState *S, Proto *p, TString **sl) {
- lua_State *L = S->L;
- TString *ts;
- TValue sv;
- size_t size = loadSize(S);
- if (size == 0) { /* previously saved string? */
- lua_Unsigned idx = loadVarint(S, LUA_MAXUNSIGNED); /* get its index */
- TValue stv;
- if (idx == 0) { /* no string? */
- lua_assert(*sl == NULL); /* must be prefilled */
- return;
- }
- if (novariant(luaH_getint(S->h, l_castU2S(idx), &stv)) != LUA_TSTRING)
- error(S, "invalid string index");
- *sl = ts = tsvalue(&stv); /* get its value */
- luaC_objbarrier(L, p, ts);
- return; /* do not save it again */
- }
- else if ((size -= 1) <= LUAI_MAXSHORTLEN) { /* short string? */
- char buff[LUAI_MAXSHORTLEN + 1]; /* extra space for '\0' */
- loadVector(S, buff, size + 1); /* load string into buffer */
- *sl = ts = luaS_newlstr(L, buff, size); /* create string */
- luaC_objbarrier(L, p, ts);
- }
- else if (S->fixed) { /* for a fixed buffer, use a fixed string */
- const char *s = getaddr(S, size + 1, char); /* get content address */
- *sl = ts = luaS_newextlstr(L, s, size, NULL, NULL);
- luaC_objbarrier(L, p, ts);
- }
- else { /* create internal copy */
- *sl = ts = luaS_createlngstrobj(L, size); /* create string */
- luaC_objbarrier(L, p, ts);
- loadVector(S, getlngstr(ts), size + 1); /* load directly in final place */
- }
- /* add string to list of saved strings */
- S->nstr++;
- setsvalue(L, &sv, ts);
- luaH_setint(L, S->h, l_castU2S(S->nstr), &sv);
- luaC_objbarrierback(L, obj2gco(S->h), ts);
-}
-
-
-static void loadCode (LoadState *S, Proto *f) {
- int n = loadInt(S);
- loadAlign(S, sizeof(f->code[0]));
- if (S->fixed) {
- f->code = getaddr(S, n, Instruction);
- f->sizecode = n;
- }
- else {
- f->code = luaM_newvectorchecked(S->L, n, Instruction);
- f->sizecode = n;
- loadVector(S, f->code, n);
- }
-}
-
-
-static void loadFunction(LoadState *S, Proto *f);
-
-
-static void loadConstants (LoadState *S, Proto *f) {
- int i;
- int n = loadInt(S);
- f->k = luaM_newvectorchecked(S->L, n, TValue);
- f->sizek = n;
- for (i = 0; i < n; i++)
- setnilvalue(&f->k[i]);
- for (i = 0; i < n; i++) {
- TValue *o = &f->k[i];
- int t = loadByte(S);
- switch (t) {
- case LUA_VNIL:
- setnilvalue(o);
- break;
- case LUA_VFALSE:
- setbfvalue(o);
- break;
- case LUA_VTRUE:
- setbtvalue(o);
- break;
- case LUA_VNUMFLT:
- setfltvalue(o, loadNumber(S));
- break;
- case LUA_VNUMINT:
- setivalue(o, loadInteger(S));
- break;
- case LUA_VSHRSTR:
- case LUA_VLNGSTR: {
- lua_assert(f->source == NULL);
- loadString(S, f, &f->source); /* use 'source' to anchor string */
- if (f->source == NULL)
- error(S, "bad format for constant string");
- setsvalue2n(S->L, o, f->source); /* save it in the right place */
- f->source = NULL;
- break;
- }
- default: error(S, "invalid constant");
- }
- }
-}
-
-
-static void loadProtos (LoadState *S, Proto *f) {
- int i;
- int n = loadInt(S);
- f->p = luaM_newvectorchecked(S->L, n, Proto *);
- f->sizep = n;
- for (i = 0; i < n; i++)
- f->p[i] = NULL;
- for (i = 0; i < n; i++) {
- f->p[i] = luaF_newproto(S->L);
- luaC_objbarrier(S->L, f, f->p[i]);
- loadFunction(S, f->p[i]);
- }
-}
-
-
-/*
-** Load the upvalues for a function. The names must be filled first,
-** because the filling of the other fields can raise read errors and
-** the creation of the error message can call an emergency collection;
-** in that case all prototypes must be consistent for the GC.
-*/
-static void loadUpvalues (LoadState *S, Proto *f) {
- int i;
- int n = loadInt(S);
- f->upvalues = luaM_newvectorchecked(S->L, n, Upvaldesc);
- f->sizeupvalues = n;
- for (i = 0; i < n; i++) /* make array valid for GC */
- f->upvalues[i].name = NULL;
- for (i = 0; i < n; i++) { /* following calls can raise errors */
- f->upvalues[i].instack = loadByte(S);
- f->upvalues[i].idx = loadByte(S);
- f->upvalues[i].kind = loadByte(S);
- }
-}
-
-
-static void loadDebug (LoadState *S, Proto *f) {
- int i;
- int n = loadInt(S);
- if (S->fixed) {
- f->lineinfo = getaddr(S, n, ls_byte);
- f->sizelineinfo = n;
- }
- else {
- f->lineinfo = luaM_newvectorchecked(S->L, n, ls_byte);
- f->sizelineinfo = n;
- loadVector(S, f->lineinfo, n);
- }
- n = loadInt(S);
- if (n > 0) {
- loadAlign(S, sizeof(int));
- if (S->fixed) {
- f->abslineinfo = getaddr(S, n, AbsLineInfo);
- f->sizeabslineinfo = n;
- }
- else {
- f->abslineinfo = luaM_newvectorchecked(S->L, n, AbsLineInfo);
- f->sizeabslineinfo = n;
- loadVector(S, f->abslineinfo, n);
- }
- }
- n = loadInt(S);
- f->locvars = luaM_newvectorchecked(S->L, n, LocVar);
- f->sizelocvars = n;
- for (i = 0; i < n; i++)
- f->locvars[i].varname = NULL;
- for (i = 0; i < n; i++) {
- loadString(S, f, &f->locvars[i].varname);
- f->locvars[i].startpc = loadInt(S);
- f->locvars[i].endpc = loadInt(S);
- }
- n = loadInt(S);
- if (n != 0) /* does it have debug information? */
- n = f->sizeupvalues; /* must be this many */
- for (i = 0; i < n; i++)
- loadString(S, f, &f->upvalues[i].name);
-}
-
-
-static void loadFunction (LoadState *S, Proto *f) {
- f->linedefined = loadInt(S);
- f->lastlinedefined = loadInt(S);
- f->numparams = loadByte(S);
- /* get only the meaningful flags */
- f->flag = cast_byte(loadByte(S) & ~PF_FIXED);
- if (S->fixed)
- f->flag |= PF_FIXED; /* signal that code is fixed */
- f->maxstacksize = loadByte(S);
- loadCode(S, f);
- loadConstants(S, f);
- loadUpvalues(S, f);
- loadProtos(S, f);
- loadString(S, f, &f->source);
- loadDebug(S, f);
-}
-
-
-static void checkliteral (LoadState *S, const char *s, const char *msg) {
- char buff[sizeof(LUA_SIGNATURE) + sizeof(LUAC_DATA)]; /* larger than both */
- size_t len = strlen(s);
- loadVector(S, buff, len);
- if (memcmp(s, buff, len) != 0)
- error(S, msg);
-}
-
-
-static l_noret numerror (LoadState *S, const char *what, const char *tname) {
- const char *msg = luaO_pushfstring(S->L, "%s %s mismatch", tname, what);
- error(S, msg);
-}
-
-
-static void checknumsize (LoadState *S, int size, const char *tname) {
- if (size != loadByte(S))
- numerror(S, "size", tname);
-}
-
-
-static void checknumformat (LoadState *S, int eq, const char *tname) {
- if (!eq)
- numerror(S, "format", tname);
-}
-
-
-#define checknum(S,tvar,value,tname) \
- { tvar i; checknumsize(S, sizeof(i), tname); \
- loadVar(S, i); \
- checknumformat(S, i == value, tname); }
-
-
-static void checkHeader (LoadState *S) {
- /* skip 1st char (already read and checked) */
- checkliteral(S, &LUA_SIGNATURE[1], "not a binary chunk");
- if (loadByte(S) != LUAC_VERSION)
- error(S, "version mismatch");
- if (loadByte(S) != LUAC_FORMAT)
- error(S, "format mismatch");
- checkliteral(S, LUAC_DATA, "corrupted chunk");
- checknum(S, int, LUAC_INT, "int");
- checknum(S, Instruction, LUAC_INST, "instruction");
- checknum(S, lua_Integer, LUAC_INT, "Lua integer");
- checknum(S, lua_Number, LUAC_NUM, "Lua number");
-}
-
-
-/*
-** Load precompiled chunk.
-*/
-LClosure *luaU_undump (lua_State *L, ZIO *Z, const char *name, int fixed) {
- LoadState S;
- LClosure *cl;
- if (*name == '@' || *name == '=')
- name = name + 1;
- else if (*name == LUA_SIGNATURE[0])
- name = "binary string";
- S.name = name;
- S.L = L;
- S.Z = Z;
- S.fixed = cast_byte(fixed);
- S.offset = 1; /* fist byte was already read */
- checkHeader(&S);
- cl = luaF_newLclosure(L, loadByte(&S));
- setclLvalue2s(L, L->top.p, cl);
- luaD_inctop(L);
- S.h = luaH_new(L); /* create list of saved strings */
- S.nstr = 0;
- sethvalue2s(L, L->top.p, S.h); /* anchor it */
- luaD_inctop(L);
- cl->p = luaF_newproto(L);
- luaC_objbarrier(L, cl, cl->p);
- loadFunction(&S, cl->p);
- if (cl->nupvalues != cl->p->sizeupvalues)
- error(&S, "corrupted chunk");
- luai_verifycode(L, cl->p);
- L->top.p--; /* pop table */
- return cl;
-}
-
diff --git a/lutf8lib.c b/lutf8lib.c
deleted file mode 100644
index 0cd7f9c363..0000000000
--- a/lutf8lib.c
+++ /dev/null
@@ -1,294 +0,0 @@
-/*
-** $Id: lutf8lib.c $
-** Standard library for UTF-8 manipulation
-** See Copyright Notice in lua.h
-*/
-
-#define lutf8lib_c
-#define LUA_LIB
-
-#include "lprefix.h"
-
-
-#include
-#include
-#include
-
-#include "lua.h"
-
-#include "lauxlib.h"
-#include "lualib.h"
-#include "llimits.h"
-
-
-#define MAXUNICODE 0x10FFFFu
-
-#define MAXUTF 0x7FFFFFFFu
-
-
-#define MSGInvalid "invalid UTF-8 code"
-
-
-#define iscont(c) (((c) & 0xC0) == 0x80)
-#define iscontp(p) iscont(*(p))
-
-
-/* from strlib */
-/* translate a relative string position: negative means back from end */
-static lua_Integer u_posrelat (lua_Integer pos, size_t len) {
- if (pos >= 0) return pos;
- else if (0u - (size_t)pos > len) return 0;
- else return (lua_Integer)len + pos + 1;
-}
-
-
-/*
-** Decode one UTF-8 sequence, returning NULL if byte sequence is
-** invalid. The array 'limits' stores the minimum value for each
-** sequence length, to check for overlong representations. Its first
-** entry forces an error for non-ASCII bytes with no continuation
-** bytes (count == 0).
-*/
-static const char *utf8_decode (const char *s, l_uint32 *val, int strict) {
- static const l_uint32 limits[] =
- {~(l_uint32)0, 0x80, 0x800, 0x10000u, 0x200000u, 0x4000000u};
- unsigned int c = (unsigned char)s[0];
- l_uint32 res = 0; /* final result */
- if (c < 0x80) /* ASCII? */
- res = c;
- else if (c >= 0xfe) /* c >= 1111 1110b ? */
- return NULL; /* would need six or more continuation bytes */
- else {
- int count = 0; /* to count number of continuation bytes */
- for (; c & 0x40; c <<= 1) { /* while it needs continuation bytes... */
- unsigned int cc = (unsigned char)s[++count]; /* read next byte */
- if (!iscont(cc)) /* not a continuation byte? */
- return NULL; /* invalid byte sequence */
- res = (res << 6) | (cc & 0x3F); /* add lower 6 bits from cont. byte */
- }
- lua_assert(count <= 5);
- res |= ((l_uint32)(c & 0x7F) << (count * 5)); /* add first byte */
- if (res > MAXUTF || res < limits[count])
- return NULL; /* invalid byte sequence */
- s += count; /* skip continuation bytes read */
- }
- if (strict) {
- /* check for invalid code points; too large or surrogates */
- if (res > MAXUNICODE || (0xD800u <= res && res <= 0xDFFFu))
- return NULL;
- }
- if (val) *val = res;
- return s + 1; /* +1 to include first byte */
-}
-
-
-/*
-** utf8len(s [, i [, j [, lax]]]) --> number of characters that
-** start in the range [i,j], or nil + current position if 's' is not
-** well formed in that interval
-*/
-static int utflen (lua_State *L) {
- lua_Integer n = 0; /* counter for the number of characters */
- size_t len; /* string length in bytes */
- const char *s = luaL_checklstring(L, 1, &len);
- lua_Integer posi = u_posrelat(luaL_optinteger(L, 2, 1), len);
- lua_Integer posj = u_posrelat(luaL_optinteger(L, 3, -1), len);
- int lax = lua_toboolean(L, 4);
- luaL_argcheck(L, 1 <= posi && --posi <= (lua_Integer)len, 2,
- "initial position out of bounds");
- luaL_argcheck(L, --posj < (lua_Integer)len, 3,
- "final position out of bounds");
- while (posi <= posj) {
- const char *s1 = utf8_decode(s + posi, NULL, !lax);
- if (s1 == NULL) { /* conversion error? */
- luaL_pushfail(L); /* return fail ... */
- lua_pushinteger(L, posi + 1); /* ... and current position */
- return 2;
- }
- posi = ct_diff2S(s1 - s);
- n++;
- }
- lua_pushinteger(L, n);
- return 1;
-}
-
-
-/*
-** codepoint(s, [i, [j [, lax]]]) -> returns codepoints for all
-** characters that start in the range [i,j]
-*/
-static int codepoint (lua_State *L) {
- size_t len;
- const char *s = luaL_checklstring(L, 1, &len);
- lua_Integer posi = u_posrelat(luaL_optinteger(L, 2, 1), len);
- lua_Integer pose = u_posrelat(luaL_optinteger(L, 3, posi), len);
- int lax = lua_toboolean(L, 4);
- int n;
- const char *se;
- luaL_argcheck(L, posi >= 1, 2, "out of bounds");
- luaL_argcheck(L, pose <= (lua_Integer)len, 3, "out of bounds");
- if (posi > pose) return 0; /* empty interval; return no values */
- if (pose - posi >= INT_MAX) /* (lua_Integer -> int) overflow? */
- return luaL_error(L, "string slice too long");
- n = (int)(pose - posi) + 1; /* upper bound for number of returns */
- luaL_checkstack(L, n, "string slice too long");
- n = 0; /* count the number of returns */
- se = s + pose; /* string end */
- for (s += posi - 1; s < se;) {
- l_uint32 code;
- s = utf8_decode(s, &code, !lax);
- if (s == NULL)
- return luaL_error(L, MSGInvalid);
- lua_pushinteger(L, l_castU2S(code));
- n++;
- }
- return n;
-}
-
-
-static void pushutfchar (lua_State *L, int arg) {
- lua_Unsigned code = (lua_Unsigned)luaL_checkinteger(L, arg);
- luaL_argcheck(L, code <= MAXUTF, arg, "value out of range");
- lua_pushfstring(L, "%U", cast(unsigned long, code));
-}
-
-
-/*
-** utfchar(n1, n2, ...) -> char(n1)..char(n2)...
-*/
-static int utfchar (lua_State *L) {
- int n = lua_gettop(L); /* number of arguments */
- if (n == 1) /* optimize common case of single char */
- pushutfchar(L, 1);
- else {
- int i;
- luaL_Buffer b;
- luaL_buffinit(L, &b);
- for (i = 1; i <= n; i++) {
- pushutfchar(L, i);
- luaL_addvalue(&b);
- }
- luaL_pushresult(&b);
- }
- return 1;
-}
-
-
-/*
-** offset(s, n, [i]) -> indices where n-th character counting from
-** position 'i' starts and ends; 0 means character at 'i'.
-*/
-static int byteoffset (lua_State *L) {
- size_t len;
- const char *s = luaL_checklstring(L, 1, &len);
- lua_Integer n = luaL_checkinteger(L, 2);
- lua_Integer posi = (n >= 0) ? 1 : cast_st2S(len) + 1;
- posi = u_posrelat(luaL_optinteger(L, 3, posi), len);
- luaL_argcheck(L, 1 <= posi && --posi <= (lua_Integer)len, 3,
- "position out of bounds");
- if (n == 0) {
- /* find beginning of current byte sequence */
- while (posi > 0 && iscontp(s + posi)) posi--;
- }
- else {
- if (iscontp(s + posi))
- return luaL_error(L, "initial position is a continuation byte");
- if (n < 0) {
- while (n < 0 && posi > 0) { /* move back */
- do { /* find beginning of previous character */
- posi--;
- } while (posi > 0 && iscontp(s + posi));
- n++;
- }
- }
- else {
- n--; /* do not move for 1st character */
- while (n > 0 && posi < (lua_Integer)len) {
- do { /* find beginning of next character */
- posi++;
- } while (iscontp(s + posi)); /* (cannot pass final '\0') */
- n--;
- }
- }
- }
- if (n != 0) { /* did not find given character? */
- luaL_pushfail(L);
- return 1;
- }
- lua_pushinteger(L, posi + 1); /* initial position */
- if ((s[posi] & 0x80) != 0) { /* multi-byte character? */
- if (iscont(s[posi]))
- return luaL_error(L, "initial position is a continuation byte");
- while (iscontp(s + posi + 1))
- posi++; /* skip to last continuation byte */
- }
- /* else one-byte character: final position is the initial one */
- lua_pushinteger(L, posi + 1); /* 'posi' now is the final position */
- return 2;
-}
-
-
-static int iter_aux (lua_State *L, int strict) {
- size_t len;
- const char *s = luaL_checklstring(L, 1, &len);
- lua_Unsigned n = (lua_Unsigned)lua_tointeger(L, 2);
- if (n < len) {
- while (iscontp(s + n)) n++; /* go to next character */
- }
- if (n >= len) /* (also handles original 'n' being negative) */
- return 0; /* no more codepoints */
- else {
- l_uint32 code;
- const char *next = utf8_decode(s + n, &code, strict);
- if (next == NULL || iscontp(next))
- return luaL_error(L, MSGInvalid);
- lua_pushinteger(L, l_castU2S(n + 1));
- lua_pushinteger(L, l_castU2S(code));
- return 2;
- }
-}
-
-
-static int iter_auxstrict (lua_State *L) {
- return iter_aux(L, 1);
-}
-
-static int iter_auxlax (lua_State *L) {
- return iter_aux(L, 0);
-}
-
-
-static int iter_codes (lua_State *L) {
- int lax = lua_toboolean(L, 2);
- const char *s = luaL_checkstring(L, 1);
- luaL_argcheck(L, !iscontp(s), 1, MSGInvalid);
- lua_pushcfunction(L, lax ? iter_auxlax : iter_auxstrict);
- lua_pushvalue(L, 1);
- lua_pushinteger(L, 0);
- return 3;
-}
-
-
-/* pattern to match a single UTF-8 character */
-#define UTF8PATT "[\0-\x7F\xC2-\xFD][\x80-\xBF]*"
-
-
-static const luaL_Reg funcs[] = {
- {"offset", byteoffset},
- {"codepoint", codepoint},
- {"char", utfchar},
- {"len", utflen},
- {"codes", iter_codes},
- /* placeholders */
- {"charpattern", NULL},
- {NULL, NULL}
-};
-
-
-LUAMOD_API int luaopen_utf8 (lua_State *L) {
- luaL_newlib(L, funcs);
- lua_pushlstring(L, UTF8PATT, sizeof(UTF8PATT)/sizeof(char) - 1);
- lua_setfield(L, -2, "charpattern");
- return 1;
-}
-
diff --git a/lvm.c b/lvm.c
deleted file mode 100644
index 96ae16390f..0000000000
--- a/lvm.c
+++ /dev/null
@@ -1,1972 +0,0 @@
-/*
-** $Id: lvm.c $
-** Lua virtual machine
-** See Copyright Notice in lua.h
-*/
-
-#define lvm_c
-#define LUA_CORE
-
-#include "lprefix.h"
-
-#include
-#include
-#include
-#include
-#include
-#include
-
-#include "lua.h"
-
-#include "lapi.h"
-#include "ldebug.h"
-#include "ldo.h"
-#include "lfunc.h"
-#include "lgc.h"
-#include "lobject.h"
-#include "lopcodes.h"
-#include "lstate.h"
-#include "lstring.h"
-#include "ltable.h"
-#include "ltm.h"
-#include "lvm.h"
-
-
-/*
-** By default, use jump tables in the main interpreter loop on gcc
-** and compatible compilers.
-*/
-#if !defined(LUA_USE_JUMPTABLE)
-#if defined(__GNUC__)
-#define LUA_USE_JUMPTABLE 1
-#else
-#define LUA_USE_JUMPTABLE 0
-#endif
-#endif
-
-
-
-/* limit for table tag-method chains (to avoid infinite loops) */
-#define MAXTAGLOOP 2000
-
-
-/*
-** 'l_intfitsf' checks whether a given integer is in the range that
-** can be converted to a float without rounding. Used in comparisons.
-*/
-
-/* number of bits in the mantissa of a float */
-#define NBM (l_floatatt(MANT_DIG))
-
-/*
-** Check whether some integers may not fit in a float, testing whether
-** (maxinteger >> NBM) > 0. (That implies (1 << NBM) <= maxinteger.)
-** (The shifts are done in parts, to avoid shifting by more than the size
-** of an integer. In a worst case, NBM == 113 for long double and
-** sizeof(long) == 32.)
-*/
-#if ((((LUA_MAXINTEGER >> (NBM / 4)) >> (NBM / 4)) >> (NBM / 4)) \
- >> (NBM - (3 * (NBM / 4)))) > 0
-
-/* limit for integers that fit in a float */
-#define MAXINTFITSF ((lua_Unsigned)1 << NBM)
-
-/* check whether 'i' is in the interval [-MAXINTFITSF, MAXINTFITSF] */
-#define l_intfitsf(i) ((MAXINTFITSF + l_castS2U(i)) <= (2 * MAXINTFITSF))
-
-#else /* all integers fit in a float precisely */
-
-#define l_intfitsf(i) 1
-
-#endif
-
-
-/*
-** Try to convert a value from string to a number value.
-** If the value is not a string or is a string not representing
-** a valid numeral (or if coercions from strings to numbers
-** are disabled via macro 'cvt2num'), do not modify 'result'
-** and return 0.
-*/
-static int l_strton (const TValue *obj, TValue *result) {
- lua_assert(obj != result);
- if (!cvt2num(obj)) /* is object not a string? */
- return 0;
- else {
- TString *st = tsvalue(obj);
- size_t stlen;
- const char *s = getlstr(st, stlen);
- return (luaO_str2num(s, result) == stlen + 1);
- }
-}
-
-
-/*
-** Try to convert a value to a float. The float case is already handled
-** by the macro 'tonumber'.
-*/
-int luaV_tonumber_ (const TValue *obj, lua_Number *n) {
- TValue v;
- if (ttisinteger(obj)) {
- *n = cast_num(ivalue(obj));
- return 1;
- }
- else if (l_strton(obj, &v)) { /* string coercible to number? */
- *n = nvalue(&v); /* convert result of 'luaO_str2num' to a float */
- return 1;
- }
- else
- return 0; /* conversion failed */
-}
-
-
-/*
-** try to convert a float to an integer, rounding according to 'mode'.
-*/
-int luaV_flttointeger (lua_Number n, lua_Integer *p, F2Imod mode) {
- lua_Number f = l_floor(n);
- if (n != f) { /* not an integral value? */
- if (mode == F2Ieq) return 0; /* fails if mode demands integral value */
- else if (mode == F2Iceil) /* needs ceiling? */
- f += 1; /* convert floor to ceiling (remember: n != f) */
- }
- return lua_numbertointeger(f, p);
-}
-
-
-/*
-** try to convert a value to an integer, rounding according to 'mode',
-** without string coercion.
-** ("Fast track" handled by macro 'tointegerns'.)
-*/
-int luaV_tointegerns (const TValue *obj, lua_Integer *p, F2Imod mode) {
- if (ttisfloat(obj))
- return luaV_flttointeger(fltvalue(obj), p, mode);
- else if (ttisinteger(obj)) {
- *p = ivalue(obj);
- return 1;
- }
- else
- return 0;
-}
-
-
-/*
-** try to convert a value to an integer.
-*/
-int luaV_tointeger (const TValue *obj, lua_Integer *p, F2Imod mode) {
- TValue v;
- if (l_strton(obj, &v)) /* does 'obj' point to a numerical string? */
- obj = &v; /* change it to point to its corresponding number */
- return luaV_tointegerns(obj, p, mode);
-}
-
-
-/*
-** Try to convert a 'for' limit to an integer, preserving the semantics
-** of the loop. Return true if the loop must not run; otherwise, '*p'
-** gets the integer limit.
-** (The following explanation assumes a positive step; it is valid for
-** negative steps mutatis mutandis.)
-** If the limit is an integer or can be converted to an integer,
-** rounding down, that is the limit.
-** Otherwise, check whether the limit can be converted to a float. If
-** the float is too large, clip it to LUA_MAXINTEGER. If the float
-** is too negative, the loop should not run, because any initial
-** integer value is greater than such limit; so, the function returns
-** true to signal that. (For this latter case, no integer limit would be
-** correct; even a limit of LUA_MININTEGER would run the loop once for
-** an initial value equal to LUA_MININTEGER.)
-*/
-static int forlimit (lua_State *L, lua_Integer init, const TValue *lim,
- lua_Integer *p, lua_Integer step) {
- if (!luaV_tointeger(lim, p, (step < 0 ? F2Iceil : F2Ifloor))) {
- /* not coercible to in integer */
- lua_Number flim; /* try to convert to float */
- if (!tonumber(lim, &flim)) /* cannot convert to float? */
- luaG_forerror(L, lim, "limit");
- /* else 'flim' is a float out of integer bounds */
- if (luai_numlt(0, flim)) { /* if it is positive, it is too large */
- if (step < 0) return 1; /* initial value must be less than it */
- *p = LUA_MAXINTEGER; /* truncate */
- }
- else { /* it is less than min integer */
- if (step > 0) return 1; /* initial value must be greater than it */
- *p = LUA_MININTEGER; /* truncate */
- }
- }
- return (step > 0 ? init > *p : init < *p); /* not to run? */
-}
-
-
-/*
-** Prepare a numerical for loop (opcode OP_FORPREP).
-** Before execution, stack is as follows:
-** ra : initial value
-** ra + 1 : limit
-** ra + 2 : step
-** Return true to skip the loop. Otherwise,
-** after preparation, stack will be as follows:
-** ra : loop counter (integer loops) or limit (float loops)
-** ra + 1 : step
-** ra + 2 : control variable
-*/
-static int forprep (lua_State *L, StkId ra) {
- TValue *pinit = s2v(ra);
- TValue *plimit = s2v(ra + 1);
- TValue *pstep = s2v(ra + 2);
- if (ttisinteger(pinit) && ttisinteger(pstep)) { /* integer loop? */
- lua_Integer init = ivalue(pinit);
- lua_Integer step = ivalue(pstep);
- lua_Integer limit;
- if (step == 0)
- luaG_runerror(L, "'for' step is zero");
- if (forlimit(L, init, plimit, &limit, step))
- return 1; /* skip the loop */
- else { /* prepare loop counter */
- lua_Unsigned count;
- if (step > 0) { /* ascending loop? */
- count = l_castS2U(limit) - l_castS2U(init);
- if (step != 1) /* avoid division in the too common case */
- count /= l_castS2U(step);
- }
- else { /* step < 0; descending loop */
- count = l_castS2U(init) - l_castS2U(limit);
- /* 'step+1' avoids negating 'mininteger' */
- count /= l_castS2U(-(step + 1)) + 1u;
- }
- /* use 'chgivalue' for places that for sure had integers */
- chgivalue(s2v(ra), l_castU2S(count)); /* change init to count */
- setivalue(s2v(ra + 1), step); /* change limit to step */
- chgivalue(s2v(ra + 2), init); /* change step to init */
- }
- }
- else { /* try making all values floats */
- lua_Number init; lua_Number limit; lua_Number step;
- if (l_unlikely(!tonumber(plimit, &limit)))
- luaG_forerror(L, plimit, "limit");
- if (l_unlikely(!tonumber(pstep, &step)))
- luaG_forerror(L, pstep, "step");
- if (l_unlikely(!tonumber(pinit, &init)))
- luaG_forerror(L, pinit, "initial value");
- if (step == 0)
- luaG_runerror(L, "'for' step is zero");
- if (luai_numlt(0, step) ? luai_numlt(limit, init)
- : luai_numlt(init, limit))
- return 1; /* skip the loop */
- else {
- /* make sure all values are floats */
- setfltvalue(s2v(ra), limit);
- setfltvalue(s2v(ra + 1), step);
- setfltvalue(s2v(ra + 2), init); /* control variable */
- }
- }
- return 0;
-}
-
-
-/*
-** Execute a step of a float numerical for loop, returning
-** true iff the loop must continue. (The integer case is
-** written inline with opcode OP_FORLOOP, for performance.)
-*/
-static int floatforloop (lua_State *L, StkId ra) {
- lua_Number step = fltvalue(s2v(ra + 1));
- lua_Number limit = fltvalue(s2v(ra));
- lua_Number idx = fltvalue(s2v(ra + 2)); /* control variable */
- idx = luai_numadd(L, idx, step); /* increment index */
- if (luai_numlt(0, step) ? luai_numle(idx, limit)
- : luai_numle(limit, idx)) {
- chgfltvalue(s2v(ra + 2), idx); /* update control variable */
- return 1; /* jump back */
- }
- else
- return 0; /* finish the loop */
-}
-
-
-/*
-** Finish the table access 'val = t[key]' and return the tag of the result.
-*/
-lu_byte luaV_finishget (lua_State *L, const TValue *t, TValue *key,
- StkId val, lu_byte tag) {
- int loop; /* counter to avoid infinite loops */
- const TValue *tm; /* metamethod */
- for (loop = 0; loop < MAXTAGLOOP; loop++) {
- if (tag == LUA_VNOTABLE) { /* 't' is not a table? */
- lua_assert(!ttistable(t));
- tm = luaT_gettmbyobj(L, t, TM_INDEX);
- if (l_unlikely(notm(tm)))
- luaG_typeerror(L, t, "index"); /* no metamethod */
- /* else will try the metamethod */
- }
- else { /* 't' is a table */
- tm = fasttm(L, hvalue(t)->metatable, TM_INDEX); /* table's metamethod */
- if (tm == NULL) { /* no metamethod? */
- setnilvalue(s2v(val)); /* result is nil */
- return LUA_VNIL;
- }
- /* else will try the metamethod */
- }
- if (ttisfunction(tm)) { /* is metamethod a function? */
- tag = luaT_callTMres(L, tm, t, key, val); /* call it */
- return tag; /* return tag of the result */
- }
- t = tm; /* else try to access 'tm[key]' */
- luaV_fastget(t, key, s2v(val), luaH_get, tag);
- if (!tagisempty(tag))
- return tag; /* done */
- /* else repeat (tail call 'luaV_finishget') */
- }
- luaG_runerror(L, "'__index' chain too long; possible loop");
- return 0; /* to avoid warnings */
-}
-
-
-/*
-** Finish a table assignment 't[key] = val'.
-** About anchoring the table before the call to 'luaH_finishset':
-** This call may trigger an emergency collection. When loop>0,
-** the table being accessed is a field in some metatable. If this
-** metatable is weak and the table is not anchored, this collection
-** could collect that table while it is being updated.
-*/
-void luaV_finishset (lua_State *L, const TValue *t, TValue *key,
- TValue *val, int hres) {
- int loop; /* counter to avoid infinite loops */
- for (loop = 0; loop < MAXTAGLOOP; loop++) {
- const TValue *tm; /* '__newindex' metamethod */
- if (hres != HNOTATABLE) { /* is 't' a table? */
- Table *h = hvalue(t); /* save 't' table */
- tm = fasttm(L, h->metatable, TM_NEWINDEX); /* get metamethod */
- if (tm == NULL) { /* no metamethod? */
- sethvalue2s(L, L->top.p, h); /* anchor 't' */
- L->top.p++; /* assume EXTRA_STACK */
- luaH_finishset(L, h, key, val, hres); /* set new value */
- L->top.p--;
- invalidateTMcache(h);
- luaC_barrierback(L, obj2gco(h), val);
- return;
- }
- /* else will try the metamethod */
- }
- else { /* not a table; check metamethod */
- tm = luaT_gettmbyobj(L, t, TM_NEWINDEX);
- if (l_unlikely(notm(tm)))
- luaG_typeerror(L, t, "index");
- }
- /* try the metamethod */
- if (ttisfunction(tm)) {
- luaT_callTM(L, tm, t, key, val);
- return;
- }
- t = tm; /* else repeat assignment over 'tm' */
- luaV_fastset(t, key, val, hres, luaH_pset);
- if (hres == HOK) {
- luaV_finishfastset(L, t, val);
- return; /* done */
- }
- /* else 'return luaV_finishset(L, t, key, val, slot)' (loop) */
- }
- luaG_runerror(L, "'__newindex' chain too long; possible loop");
-}
-
-
-/*
-** Function to be used for 0-terminated string order comparison
-*/
-#if !defined(l_strcoll)
-#define l_strcoll strcoll
-#endif
-
-
-/*
-** Compare two strings 'ts1' x 'ts2', returning an integer less-equal-
-** -greater than zero if 'ts1' is less-equal-greater than 'ts2'.
-** The code is a little tricky because it allows '\0' in the strings
-** and it uses 'strcoll' (to respect locales) for each segment
-** of the strings. Note that segments can compare equal but still
-** have different lengths.
-*/
-static int l_strcmp (const TString *ts1, const TString *ts2) {
- size_t rl1; /* real length */
- const char *s1 = getlstr(ts1, rl1);
- size_t rl2;
- const char *s2 = getlstr(ts2, rl2);
- for (;;) { /* for each segment */
- int temp = l_strcoll(s1, s2);
- if (temp != 0) /* not equal? */
- return temp; /* done */
- else { /* strings are equal up to a '\0' */
- size_t zl1 = strlen(s1); /* index of first '\0' in 's1' */
- size_t zl2 = strlen(s2); /* index of first '\0' in 's2' */
- if (zl2 == rl2) /* 's2' is finished? */
- return (zl1 == rl1) ? 0 : 1; /* check 's1' */
- else if (zl1 == rl1) /* 's1' is finished? */
- return -1; /* 's1' is less than 's2' ('s2' is not finished) */
- /* both strings longer than 'zl'; go on comparing after the '\0' */
- zl1++; zl2++;
- s1 += zl1; rl1 -= zl1; s2 += zl2; rl2 -= zl2;
- }
- }
-}
-
-
-/*
-** Check whether integer 'i' is less than float 'f'. If 'i' has an
-** exact representation as a float ('l_intfitsf'), compare numbers as
-** floats. Otherwise, use the equivalence 'i < f <=> i < ceil(f)'.
-** If 'ceil(f)' is out of integer range, either 'f' is greater than
-** all integers or less than all integers.
-** (The test with 'l_intfitsf' is only for performance; the else
-** case is correct for all values, but it is slow due to the conversion
-** from float to int.)
-** When 'f' is NaN, comparisons must result in false.
-*/
-l_sinline int LTintfloat (lua_Integer i, lua_Number f) {
- if (l_intfitsf(i))
- return luai_numlt(cast_num(i), f); /* compare them as floats */
- else { /* i < f <=> i < ceil(f) */
- lua_Integer fi;
- if (luaV_flttointeger(f, &fi, F2Iceil)) /* fi = ceil(f) */
- return i < fi; /* compare them as integers */
- else /* 'f' is either greater or less than all integers */
- return f > 0; /* greater? */
- }
-}
-
-
-/*
-** Check whether integer 'i' is less than or equal to float 'f'.
-** See comments on previous function.
-*/
-l_sinline int LEintfloat (lua_Integer i, lua_Number f) {
- if (l_intfitsf(i))
- return luai_numle(cast_num(i), f); /* compare them as floats */
- else { /* i <= f <=> i <= floor(f) */
- lua_Integer fi;
- if (luaV_flttointeger(f, &fi, F2Ifloor)) /* fi = floor(f) */
- return i <= fi; /* compare them as integers */
- else /* 'f' is either greater or less than all integers */
- return f > 0; /* greater? */
- }
-}
-
-
-/*
-** Check whether float 'f' is less than integer 'i'.
-** See comments on previous function.
-*/
-l_sinline int LTfloatint (lua_Number f, lua_Integer i) {
- if (l_intfitsf(i))
- return luai_numlt(f, cast_num(i)); /* compare them as floats */
- else { /* f < i <=> floor(f) < i */
- lua_Integer fi;
- if (luaV_flttointeger(f, &fi, F2Ifloor)) /* fi = floor(f) */
- return fi < i; /* compare them as integers */
- else /* 'f' is either greater or less than all integers */
- return f < 0; /* less? */
- }
-}
-
-
-/*
-** Check whether float 'f' is less than or equal to integer 'i'.
-** See comments on previous function.
-*/
-l_sinline int LEfloatint (lua_Number f, lua_Integer i) {
- if (l_intfitsf(i))
- return luai_numle(f, cast_num(i)); /* compare them as floats */
- else { /* f <= i <=> ceil(f) <= i */
- lua_Integer fi;
- if (luaV_flttointeger(f, &fi, F2Iceil)) /* fi = ceil(f) */
- return fi <= i; /* compare them as integers */
- else /* 'f' is either greater or less than all integers */
- return f < 0; /* less? */
- }
-}
-
-
-/*
-** Return 'l < r', for numbers.
-*/
-l_sinline int LTnum (const TValue *l, const TValue *r) {
- lua_assert(ttisnumber(l) && ttisnumber(r));
- if (ttisinteger(l)) {
- lua_Integer li = ivalue(l);
- if (ttisinteger(r))
- return li < ivalue(r); /* both are integers */
- else /* 'l' is int and 'r' is float */
- return LTintfloat(li, fltvalue(r)); /* l < r ? */
- }
- else {
- lua_Number lf = fltvalue(l); /* 'l' must be float */
- if (ttisfloat(r))
- return luai_numlt(lf, fltvalue(r)); /* both are float */
- else /* 'l' is float and 'r' is int */
- return LTfloatint(lf, ivalue(r));
- }
-}
-
-
-/*
-** Return 'l <= r', for numbers.
-*/
-l_sinline int LEnum (const TValue *l, const TValue *r) {
- lua_assert(ttisnumber(l) && ttisnumber(r));
- if (ttisinteger(l)) {
- lua_Integer li = ivalue(l);
- if (ttisinteger(r))
- return li <= ivalue(r); /* both are integers */
- else /* 'l' is int and 'r' is float */
- return LEintfloat(li, fltvalue(r)); /* l <= r ? */
- }
- else {
- lua_Number lf = fltvalue(l); /* 'l' must be float */
- if (ttisfloat(r))
- return luai_numle(lf, fltvalue(r)); /* both are float */
- else /* 'l' is float and 'r' is int */
- return LEfloatint(lf, ivalue(r));
- }
-}
-
-
-/*
-** return 'l < r' for non-numbers.
-*/
-static int lessthanothers (lua_State *L, const TValue *l, const TValue *r) {
- lua_assert(!ttisnumber(l) || !ttisnumber(r));
- if (ttisstring(l) && ttisstring(r)) /* both are strings? */
- return l_strcmp(tsvalue(l), tsvalue(r)) < 0;
- else
- return luaT_callorderTM(L, l, r, TM_LT);
-}
-
-
-/*
-** Main operation less than; return 'l < r'.
-*/
-int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r) {
- if (ttisnumber(l) && ttisnumber(r)) /* both operands are numbers? */
- return LTnum(l, r);
- else return lessthanothers(L, l, r);
-}
-
-
-/*
-** return 'l <= r' for non-numbers.
-*/
-static int lessequalothers (lua_State *L, const TValue *l, const TValue *r) {
- lua_assert(!ttisnumber(l) || !ttisnumber(r));
- if (ttisstring(l) && ttisstring(r)) /* both are strings? */
- return l_strcmp(tsvalue(l), tsvalue(r)) <= 0;
- else
- return luaT_callorderTM(L, l, r, TM_LE);
-}
-
-
-/*
-** Main operation less than or equal to; return 'l <= r'.
-*/
-int luaV_lessequal (lua_State *L, const TValue *l, const TValue *r) {
- if (ttisnumber(l) && ttisnumber(r)) /* both operands are numbers? */
- return LEnum(l, r);
- else return lessequalothers(L, l, r);
-}
-
-
-/*
-** Main operation for equality of Lua values; return 't1 == t2'.
-** L == NULL means raw equality (no metamethods)
-*/
-int luaV_equalobj (lua_State *L, const TValue *t1, const TValue *t2) {
- const TValue *tm;
- if (ttype(t1) != ttype(t2)) /* not the same type? */
- return 0;
- else if (ttypetag(t1) != ttypetag(t2)) {
- switch (ttypetag(t1)) {
- case LUA_VNUMINT: { /* integer == float? */
- /* integer and float can only be equal if float has an integer
- value equal to the integer */
- lua_Integer i2;
- return (luaV_flttointeger(fltvalue(t2), &i2, F2Ieq) &&
- ivalue(t1) == i2);
- }
- case LUA_VNUMFLT: { /* float == integer? */
- lua_Integer i1; /* see comment in previous case */
- return (luaV_flttointeger(fltvalue(t1), &i1, F2Ieq) &&
- i1 == ivalue(t2));
- }
- case LUA_VSHRSTR: case LUA_VLNGSTR: {
- /* compare two strings with different variants: they can be
- equal when one string is a short string and the other is
- an external string */
- return luaS_eqstr(tsvalue(t1), tsvalue(t2));
- }
- default:
- /* only numbers (integer/float) and strings (long/short) can have
- equal values with different variants */
- return 0;
- }
- }
- else { /* equal variants */
- switch (ttypetag(t1)) {
- case LUA_VNIL: case LUA_VFALSE: case LUA_VTRUE:
- return 1;
- case LUA_VNUMINT:
- return (ivalue(t1) == ivalue(t2));
- case LUA_VNUMFLT:
- return (fltvalue(t1) == fltvalue(t2));
- case LUA_VLIGHTUSERDATA: return pvalue(t1) == pvalue(t2);
- case LUA_VSHRSTR:
- return eqshrstr(tsvalue(t1), tsvalue(t2));
- case LUA_VLNGSTR:
- return luaS_eqstr(tsvalue(t1), tsvalue(t2));
- case LUA_VUSERDATA: {
- if (uvalue(t1) == uvalue(t2)) return 1;
- else if (L == NULL) return 0;
- tm = fasttm(L, uvalue(t1)->metatable, TM_EQ);
- if (tm == NULL)
- tm = fasttm(L, uvalue(t2)->metatable, TM_EQ);
- break; /* will try TM */
- }
- case LUA_VTABLE: {
- if (hvalue(t1) == hvalue(t2)) return 1;
- else if (L == NULL) return 0;
- tm = fasttm(L, hvalue(t1)->metatable, TM_EQ);
- if (tm == NULL)
- tm = fasttm(L, hvalue(t2)->metatable, TM_EQ);
- break; /* will try TM */
- }
- case LUA_VLCF:
- return (fvalue(t1) == fvalue(t2));
- default: /* functions and threads */
- return (gcvalue(t1) == gcvalue(t2));
- }
- if (tm == NULL) /* no TM? */
- return 0; /* objects are different */
- else {
- int tag = luaT_callTMres(L, tm, t1, t2, L->top.p); /* call TM */
- return !tagisfalse(tag);
- }
- }
-}
-
-
-/* macro used by 'luaV_concat' to ensure that element at 'o' is a string */
-#define tostring(L,o) \
- (ttisstring(o) || (cvt2str(o) && (luaO_tostring(L, o), 1)))
-
-/*
-** Check whether object is a short empty string to optimize concatenation.
-** (External strings can be empty too; they will be concatenated like
-** non-empty ones.)
-*/
-#define isemptystr(o) (ttisshrstring(o) && tsvalue(o)->shrlen == 0)
-
-/* copy strings in stack from top - n up to top - 1 to buffer */
-static void copy2buff (StkId top, int n, char *buff) {
- size_t tl = 0; /* size already copied */
- do {
- TString *st = tsvalue(s2v(top - n));
- size_t l; /* length of string being copied */
- const char *s = getlstr(st, l);
- memcpy(buff + tl, s, l * sizeof(char));
- tl += l;
- } while (--n > 0);
-}
-
-
-/*
-** Main operation for concatenation: concat 'total' values in the stack,
-** from 'L->top.p - total' up to 'L->top.p - 1'.
-*/
-void luaV_concat (lua_State *L, int total) {
- if (total == 1)
- return; /* "all" values already concatenated */
- do {
- StkId top = L->top.p;
- int n = 2; /* number of elements handled in this pass (at least 2) */
- if (!(ttisstring(s2v(top - 2)) || cvt2str(s2v(top - 2))) ||
- !tostring(L, s2v(top - 1)))
- luaT_tryconcatTM(L); /* may invalidate 'top' */
- else if (isemptystr(s2v(top - 1))) /* second operand is empty? */
- cast_void(tostring(L, s2v(top - 2))); /* result is first operand */
- else if (isemptystr(s2v(top - 2))) { /* first operand is empty string? */
- setobjs2s(L, top - 2, top - 1); /* result is second op. */
- }
- else {
- /* at least two string values; get as many as possible */
- size_t tl = tsslen(tsvalue(s2v(top - 1))); /* total length */
- TString *ts;
- /* collect total length and number of strings */
- for (n = 1; n < total && tostring(L, s2v(top - n - 1)); n++) {
- size_t l = tsslen(tsvalue(s2v(top - n - 1)));
- if (l_unlikely(l >= MAX_SIZE - sizeof(TString) - tl)) {
- L->top.p = top - total; /* pop strings to avoid wasting stack */
- luaG_runerror(L, "string length overflow");
- }
- tl += l;
- }
- if (tl <= LUAI_MAXSHORTLEN) { /* is result a short string? */
- char buff[LUAI_MAXSHORTLEN];
- copy2buff(top, n, buff); /* copy strings to buffer */
- ts = luaS_newlstr(L, buff, tl);
- }
- else { /* long string; copy strings directly to final result */
- ts = luaS_createlngstrobj(L, tl);
- copy2buff(top, n, getlngstr(ts));
- }
- setsvalue2s(L, top - n, ts); /* create result */
- }
- total -= n - 1; /* got 'n' strings to create one new */
- L->top.p -= n - 1; /* popped 'n' strings and pushed one */
- } while (total > 1); /* repeat until only 1 result left */
-}
-
-
-/*
-** Main operation 'ra = #rb'.
-*/
-void luaV_objlen (lua_State *L, StkId ra, const TValue *rb) {
- const TValue *tm;
- switch (ttypetag(rb)) {
- case LUA_VTABLE: {
- Table *h = hvalue(rb);
- tm = fasttm(L, h->metatable, TM_LEN);
- if (tm) break; /* metamethod? break switch to call it */
- setivalue(s2v(ra), l_castU2S(luaH_getn(L, h))); /* else primitive len */
- return;
- }
- case LUA_VSHRSTR: {
- setivalue(s2v(ra), tsvalue(rb)->shrlen);
- return;
- }
- case LUA_VLNGSTR: {
- setivalue(s2v(ra), cast_st2S(tsvalue(rb)->u.lnglen));
- return;
- }
- default: { /* try metamethod */
- tm = luaT_gettmbyobj(L, rb, TM_LEN);
- if (l_unlikely(notm(tm))) /* no metamethod? */
- luaG_typeerror(L, rb, "get length of");
- break;
- }
- }
- luaT_callTMres(L, tm, rb, rb, ra);
-}
-
-
-/*
-** Integer division; return 'm // n', that is, floor(m/n).
-** C division truncates its result (rounds towards zero).
-** 'floor(q) == trunc(q)' when 'q >= 0' or when 'q' is integer,
-** otherwise 'floor(q) == trunc(q) - 1'.
-*/
-lua_Integer luaV_idiv (lua_State *L, lua_Integer m, lua_Integer n) {
- if (l_unlikely(l_castS2U(n) + 1u <= 1u)) { /* special cases: -1 or 0 */
- if (n == 0)
- luaG_runerror(L, "attempt to divide by zero");
- return intop(-, 0, m); /* n==-1; avoid overflow with 0x80000...//-1 */
- }
- else {
- lua_Integer q = m / n; /* perform C division */
- if ((m ^ n) < 0 && m % n != 0) /* 'm/n' would be negative non-integer? */
- q -= 1; /* correct result for different rounding */
- return q;
- }
-}
-
-
-/*
-** Integer modulus; return 'm % n'. (Assume that C '%' with
-** negative operands follows C99 behavior. See previous comment
-** about luaV_idiv.)
-*/
-lua_Integer luaV_mod (lua_State *L, lua_Integer m, lua_Integer n) {
- if (l_unlikely(l_castS2U(n) + 1u <= 1u)) { /* special cases: -1 or 0 */
- if (n == 0)
- luaG_runerror(L, "attempt to perform 'n%%0'");
- return 0; /* m % -1 == 0; avoid overflow with 0x80000...%-1 */
- }
- else {
- lua_Integer r = m % n;
- if (r != 0 && (r ^ n) < 0) /* 'm/n' would be non-integer negative? */
- r += n; /* correct result for different rounding */
- return r;
- }
-}
-
-
-/*
-** Float modulus
-*/
-lua_Number luaV_modf (lua_State *L, lua_Number m, lua_Number n) {
- lua_Number r;
- luai_nummod(L, m, n, r);
- return r;
-}
-
-
-/* number of bits in an integer */
-#define NBITS l_numbits(lua_Integer)
-
-
-/*
-** Shift left operation. (Shift right just negates 'y'.)
-*/
-lua_Integer luaV_shiftl (lua_Integer x, lua_Integer y) {
- if (y < 0) { /* shift right? */
- if (y <= -NBITS) return 0;
- else return intop(>>, x, -y);
- }
- else { /* shift left */
- if (y >= NBITS) return 0;
- else return intop(<<, x, y);
- }
-}
-
-
-/*
-** create a new Lua closure, push it in the stack, and initialize
-** its upvalues.
-*/
-static void pushclosure (lua_State *L, Proto *p, UpVal **encup, StkId base,
- StkId ra) {
- int nup = p->sizeupvalues;
- Upvaldesc *uv = p->upvalues;
- int i;
- LClosure *ncl = luaF_newLclosure(L, nup);
- ncl->p = p;
- setclLvalue2s(L, ra, ncl); /* anchor new closure in stack */
- for (i = 0; i < nup; i++) { /* fill in its upvalues */
- if (uv[i].instack) /* upvalue refers to local variable? */
- ncl->upvals[i] = luaF_findupval(L, base + uv[i].idx);
- else /* get upvalue from enclosing function */
- ncl->upvals[i] = encup[uv[i].idx];
- luaC_objbarrier(L, ncl, ncl->upvals[i]);
- }
-}
-
-
-/*
-** finish execution of an opcode interrupted by a yield
-*/
-void luaV_finishOp (lua_State *L) {
- CallInfo *ci = L->ci;
- StkId base = ci->func.p + 1;
- Instruction inst = *(ci->u.l.savedpc - 1); /* interrupted instruction */
- OpCode op = GET_OPCODE(inst);
- switch (op) { /* finish its execution */
- case OP_MMBIN: case OP_MMBINI: case OP_MMBINK: {
- setobjs2s(L, base + GETARG_A(*(ci->u.l.savedpc - 2)), --L->top.p);
- break;
- }
- case OP_UNM: case OP_BNOT: case OP_LEN:
- case OP_GETTABUP: case OP_GETTABLE: case OP_GETI:
- case OP_GETFIELD: case OP_SELF: {
- setobjs2s(L, base + GETARG_A(inst), --L->top.p);
- break;
- }
- case OP_LT: case OP_LE:
- case OP_LTI: case OP_LEI:
- case OP_GTI: case OP_GEI:
- case OP_EQ: { /* note that 'OP_EQI'/'OP_EQK' cannot yield */
- int res = !l_isfalse(s2v(L->top.p - 1));
- L->top.p--;
- lua_assert(GET_OPCODE(*ci->u.l.savedpc) == OP_JMP);
- if (res != GETARG_k(inst)) /* condition failed? */
- ci->u.l.savedpc++; /* skip jump instruction */
- break;
- }
- case OP_CONCAT: {
- StkId top = L->top.p - 1; /* top when 'luaT_tryconcatTM' was called */
- int a = GETARG_A(inst); /* first element to concatenate */
- int total = cast_int(top - 1 - (base + a)); /* yet to concatenate */
- setobjs2s(L, top - 2, top); /* put TM result in proper position */
- L->top.p = top - 1; /* top is one after last element (at top-2) */
- luaV_concat(L, total); /* concat them (may yield again) */
- break;
- }
- case OP_CLOSE: { /* yielded closing variables */
- ci->u.l.savedpc--; /* repeat instruction to close other vars. */
- break;
- }
- case OP_RETURN: { /* yielded closing variables */
- StkId ra = base + GETARG_A(inst);
- /* adjust top to signal correct number of returns, in case the
- return is "up to top" ('isIT') */
- L->top.p = ra + ci->u2.nres;
- /* repeat instruction to close other vars. and complete the return */
- ci->u.l.savedpc--;
- break;
- }
- default: {
- /* only these other opcodes can yield */
- lua_assert(op == OP_TFORCALL || op == OP_CALL ||
- op == OP_TAILCALL || op == OP_SETTABUP || op == OP_SETTABLE ||
- op == OP_SETI || op == OP_SETFIELD);
- break;
- }
- }
-}
-
-
-
-
-/*
-** {==================================================================
-** Macros for arithmetic/bitwise/comparison opcodes in 'luaV_execute'
-**
-** All these macros are to be used exclusively inside the main
-** iterpreter loop (function luaV_execute) and may access directly
-** the local variables of that function (L, i, pc, ci, etc.).
-** ===================================================================
-*/
-
-#define l_addi(L,a,b) intop(+, a, b)
-#define l_subi(L,a,b) intop(-, a, b)
-#define l_muli(L,a,b) intop(*, a, b)
-#define l_band(a,b) intop(&, a, b)
-#define l_bor(a,b) intop(|, a, b)
-#define l_bxor(a,b) intop(^, a, b)
-
-#define l_lti(a,b) (a < b)
-#define l_lei(a,b) (a <= b)
-#define l_gti(a,b) (a > b)
-#define l_gei(a,b) (a >= b)
-
-
-/*
-** Arithmetic operations with immediate operands. 'iop' is the integer
-** operation, 'fop' is the float operation.
-*/
-#define op_arithI(L,iop,fop) { \
- TValue *ra = vRA(i); \
- TValue *v1 = vRB(i); \
- int imm = GETARG_sC(i); \
- if (ttisinteger(v1)) { \
- lua_Integer iv1 = ivalue(v1); \
- pc++; setivalue(ra, iop(L, iv1, imm)); \
- } \
- else if (ttisfloat(v1)) { \
- lua_Number nb = fltvalue(v1); \
- lua_Number fimm = cast_num(imm); \
- pc++; setfltvalue(ra, fop(L, nb, fimm)); \
- }}
-
-
-/*
-** Auxiliary function for arithmetic operations over floats and others
-** with two operands.
-*/
-#define op_arithf_aux(L,v1,v2,fop) { \
- lua_Number n1; lua_Number n2; \
- if (tonumberns(v1, n1) && tonumberns(v2, n2)) { \
- StkId ra = RA(i); \
- pc++; setfltvalue(s2v(ra), fop(L, n1, n2)); \
- }}
-
-
-/*
-** Arithmetic operations over floats and others with register operands.
-*/
-#define op_arithf(L,fop) { \
- TValue *v1 = vRB(i); \
- TValue *v2 = vRC(i); \
- op_arithf_aux(L, v1, v2, fop); }
-
-
-/*
-** Arithmetic operations with K operands for floats.
-*/
-#define op_arithfK(L,fop) { \
- TValue *v1 = vRB(i); \
- TValue *v2 = KC(i); lua_assert(ttisnumber(v2)); \
- op_arithf_aux(L, v1, v2, fop); }
-
-
-/*
-** Arithmetic operations over integers and floats.
-*/
-#define op_arith_aux(L,v1,v2,iop,fop) { \
- if (ttisinteger(v1) && ttisinteger(v2)) { \
- StkId ra = RA(i); \
- lua_Integer i1 = ivalue(v1); lua_Integer i2 = ivalue(v2); \
- pc++; setivalue(s2v(ra), iop(L, i1, i2)); \
- } \
- else op_arithf_aux(L, v1, v2, fop); }
-
-
-/*
-** Arithmetic operations with register operands.
-*/
-#define op_arith(L,iop,fop) { \
- TValue *v1 = vRB(i); \
- TValue *v2 = vRC(i); \
- op_arith_aux(L, v1, v2, iop, fop); }
-
-
-/*
-** Arithmetic operations with K operands.
-*/
-#define op_arithK(L,iop,fop) { \
- TValue *v1 = vRB(i); \
- TValue *v2 = KC(i); lua_assert(ttisnumber(v2)); \
- op_arith_aux(L, v1, v2, iop, fop); }
-
-
-/*
-** Bitwise operations with constant operand.
-*/
-#define op_bitwiseK(L,op) { \
- TValue *v1 = vRB(i); \
- TValue *v2 = KC(i); \
- lua_Integer i1; \
- lua_Integer i2 = ivalue(v2); \
- if (tointegerns(v1, &i1)) { \
- StkId ra = RA(i); \
- pc++; setivalue(s2v(ra), op(i1, i2)); \
- }}
-
-
-/*
-** Bitwise operations with register operands.
-*/
-#define op_bitwise(L,op) { \
- TValue *v1 = vRB(i); \
- TValue *v2 = vRC(i); \
- lua_Integer i1; lua_Integer i2; \
- if (tointegerns(v1, &i1) && tointegerns(v2, &i2)) { \
- StkId ra = RA(i); \
- pc++; setivalue(s2v(ra), op(i1, i2)); \
- }}
-
-
-/*
-** Order operations with register operands. 'opn' actually works
-** for all numbers, but the fast track improves performance for
-** integers.
-*/
-#define op_order(L,opi,opn,other) { \
- TValue *ra = vRA(i); \
- int cond; \
- TValue *rb = vRB(i); \
- if (ttisinteger(ra) && ttisinteger(rb)) { \
- lua_Integer ia = ivalue(ra); \
- lua_Integer ib = ivalue(rb); \
- cond = opi(ia, ib); \
- } \
- else if (ttisnumber(ra) && ttisnumber(rb)) \
- cond = opn(ra, rb); \
- else \
- Protect(cond = other(L, ra, rb)); \
- docondjump(); }
-
-
-/*
-** Order operations with immediate operand. (Immediate operand is
-** always small enough to have an exact representation as a float.)
-*/
-#define op_orderI(L,opi,opf,inv,tm) { \
- TValue *ra = vRA(i); \
- int cond; \
- int im = GETARG_sB(i); \
- if (ttisinteger(ra)) \
- cond = opi(ivalue(ra), im); \
- else if (ttisfloat(ra)) { \
- lua_Number fa = fltvalue(ra); \
- lua_Number fim = cast_num(im); \
- cond = opf(fa, fim); \
- } \
- else { \
- int isf = GETARG_C(i); \
- Protect(cond = luaT_callorderiTM(L, ra, im, inv, isf, tm)); \
- } \
- docondjump(); }
-
-/* }================================================================== */
-
-
-/*
-** {==================================================================
-** Function 'luaV_execute': main interpreter loop
-** ===================================================================
-*/
-
-/*
-** some macros for common tasks in 'luaV_execute'
-*/
-
-
-#define RA(i) (base+GETARG_A(i))
-#define vRA(i) s2v(RA(i))
-#define RB(i) (base+GETARG_B(i))
-#define vRB(i) s2v(RB(i))
-#define KB(i) (k+GETARG_B(i))
-#define RC(i) (base+GETARG_C(i))
-#define vRC(i) s2v(RC(i))
-#define KC(i) (k+GETARG_C(i))
-#define RKC(i) ((TESTARG_k(i)) ? k + GETARG_C(i) : s2v(base + GETARG_C(i)))
-
-
-
-#define updatetrap(ci) (trap = ci->u.l.trap)
-
-#define updatebase(ci) (base = ci->func.p + 1)
-
-
-#define updatestack(ci) \
- { if (l_unlikely(trap)) { updatebase(ci); ra = RA(i); } }
-
-
-/*
-** Execute a jump instruction. The 'updatetrap' allows signals to stop
-** tight loops. (Without it, the local copy of 'trap' could never change.)
-*/
-#define dojump(ci,i,e) { pc += GETARG_sJ(i) + e; updatetrap(ci); }
-
-
-/* for test instructions, execute the jump instruction that follows it */
-#define donextjump(ci) { Instruction ni = *pc; dojump(ci, ni, 1); }
-
-/*
-** do a conditional jump: skip next instruction if 'cond' is not what
-** was expected (parameter 'k'), else do next instruction, which must
-** be a jump.
-*/
-#define docondjump() if (cond != GETARG_k(i)) pc++; else donextjump(ci);
-
-
-/*
-** Correct global 'pc'.
-*/
-#define savepc(ci) (ci->u.l.savedpc = pc)
-
-
-/*
-** Whenever code can raise errors, the global 'pc' and the global
-** 'top' must be correct to report occasional errors.
-*/
-#define savestate(L,ci) (savepc(ci), L->top.p = ci->top.p)
-
-
-/*
-** Protect code that, in general, can raise errors, reallocate the
-** stack, and change the hooks.
-*/
-#define Protect(exp) (savestate(L,ci), (exp), updatetrap(ci))
-
-/* special version that does not change the top */
-#define ProtectNT(exp) (savepc(ci), (exp), updatetrap(ci))
-
-/*
-** Protect code that can only raise errors. (That is, it cannot change
-** the stack or hooks.)
-*/
-#define halfProtect(exp) (savestate(L,ci), (exp))
-
-/*
-** macro executed during Lua functions at points where the
-** function can yield.
-*/
-#if !defined(luai_threadyield)
-#define luai_threadyield(L) {lua_unlock(L); lua_lock(L);}
-#endif
-
-/* 'c' is the limit of live values in the stack */
-#define checkGC(L,c) \
- { luaC_condGC(L, (savepc(ci), L->top.p = (c)), \
- updatetrap(ci)); \
- luai_threadyield(L); }
-
-
-/* fetch an instruction and prepare its execution */
-#define vmfetch() { \
- if (l_unlikely(trap)) { /* stack reallocation or hooks? */ \
- trap = luaG_traceexec(L, pc); /* handle hooks */ \
- updatebase(ci); /* correct stack */ \
- } \
- i = *(pc++); \
-}
-
-#define vmdispatch(o) switch(o)
-#define vmcase(l) case l:
-#define vmbreak break
-
-
-void luaV_execute (lua_State *L, CallInfo *ci) {
- LClosure *cl;
- TValue *k;
- StkId base;
- const Instruction *pc;
- int trap;
-#if LUA_USE_JUMPTABLE
-#include "ljumptab.h"
-#endif
- startfunc:
- trap = L->hookmask;
- returning: /* trap already set */
- cl = ci_func(ci);
- k = cl->p->k;
- pc = ci->u.l.savedpc;
- if (l_unlikely(trap))
- trap = luaG_tracecall(L);
- base = ci->func.p + 1;
- /* main loop of interpreter */
- for (;;) {
- Instruction i; /* instruction being executed */
- vmfetch();
- #if 0
- { /* low-level line tracing for debugging Lua */
- #include "lopnames.h"
- int pcrel = pcRel(pc, cl->p);
- printf("line: %d; %s (%d)\n", luaG_getfuncline(cl->p, pcrel),
- opnames[GET_OPCODE(i)], pcrel);
- }
- #endif
- lua_assert(base == ci->func.p + 1);
- lua_assert(base <= L->top.p && L->top.p <= L->stack_last.p);
- /* for tests, invalidate top for instructions not expecting it */
- lua_assert(luaP_isIT(i) || (cast_void(L->top.p = base), 1));
- vmdispatch (GET_OPCODE(i)) {
- vmcase(OP_MOVE) {
- StkId ra = RA(i);
- setobjs2s(L, ra, RB(i));
- vmbreak;
- }
- vmcase(OP_LOADI) {
- StkId ra = RA(i);
- lua_Integer b = GETARG_sBx(i);
- setivalue(s2v(ra), b);
- vmbreak;
- }
- vmcase(OP_LOADF) {
- StkId ra = RA(i);
- int b = GETARG_sBx(i);
- setfltvalue(s2v(ra), cast_num(b));
- vmbreak;
- }
- vmcase(OP_LOADK) {
- StkId ra = RA(i);
- TValue *rb = k + GETARG_Bx(i);
- setobj2s(L, ra, rb);
- vmbreak;
- }
- vmcase(OP_LOADKX) {
- StkId ra = RA(i);
- TValue *rb;
- rb = k + GETARG_Ax(*pc); pc++;
- setobj2s(L, ra, rb);
- vmbreak;
- }
- vmcase(OP_LOADFALSE) {
- StkId ra = RA(i);
- setbfvalue(s2v(ra));
- vmbreak;
- }
- vmcase(OP_LFALSESKIP) {
- StkId ra = RA(i);
- setbfvalue(s2v(ra));
- pc++; /* skip next instruction */
- vmbreak;
- }
- vmcase(OP_LOADTRUE) {
- StkId ra = RA(i);
- setbtvalue(s2v(ra));
- vmbreak;
- }
- vmcase(OP_LOADNIL) {
- StkId ra = RA(i);
- int b = GETARG_B(i);
- do {
- setnilvalue(s2v(ra++));
- } while (b--);
- vmbreak;
- }
- vmcase(OP_GETUPVAL) {
- StkId ra = RA(i);
- int b = GETARG_B(i);
- setobj2s(L, ra, cl->upvals[b]->v.p);
- vmbreak;
- }
- vmcase(OP_SETUPVAL) {
- StkId ra = RA(i);
- UpVal *uv = cl->upvals[GETARG_B(i)];
- setobj(L, uv->v.p, s2v(ra));
- luaC_barrier(L, uv, s2v(ra));
- vmbreak;
- }
- vmcase(OP_GETTABUP) {
- StkId ra = RA(i);
- TValue *upval = cl->upvals[GETARG_B(i)]->v.p;
- TValue *rc = KC(i);
- TString *key = tsvalue(rc); /* key must be a short string */
- lu_byte tag;
- luaV_fastget(upval, key, s2v(ra), luaH_getshortstr, tag);
- if (tagisempty(tag))
- Protect(luaV_finishget(L, upval, rc, ra, tag));
- vmbreak;
- }
- vmcase(OP_GETTABLE) {
- StkId ra = RA(i);
- TValue *rb = vRB(i);
- TValue *rc = vRC(i);
- lu_byte tag;
- if (ttisinteger(rc)) { /* fast track for integers? */
- luaV_fastgeti(rb, ivalue(rc), s2v(ra), tag);
- }
- else
- luaV_fastget(rb, rc, s2v(ra), luaH_get, tag);
- if (tagisempty(tag))
- Protect(luaV_finishget(L, rb, rc, ra, tag));
- vmbreak;
- }
- vmcase(OP_GETI) {
- StkId ra = RA(i);
- TValue *rb = vRB(i);
- int c = GETARG_C(i);
- lu_byte tag;
- luaV_fastgeti(rb, c, s2v(ra), tag);
- if (tagisempty(tag)) {
- TValue key;
- setivalue(&key, c);
- Protect(luaV_finishget(L, rb, &key, ra, tag));
- }
- vmbreak;
- }
- vmcase(OP_GETFIELD) {
- StkId ra = RA(i);
- TValue *rb = vRB(i);
- TValue *rc = KC(i);
- TString *key = tsvalue(rc); /* key must be a short string */
- lu_byte tag;
- luaV_fastget(rb, key, s2v(ra), luaH_getshortstr, tag);
- if (tagisempty(tag))
- Protect(luaV_finishget(L, rb, rc, ra, tag));
- vmbreak;
- }
- vmcase(OP_SETTABUP) {
- int hres;
- TValue *upval = cl->upvals[GETARG_A(i)]->v.p;
- TValue *rb = KB(i);
- TValue *rc = RKC(i);
- TString *key = tsvalue(rb); /* key must be a short string */
- luaV_fastset(upval, key, rc, hres, luaH_psetshortstr);
- if (hres == HOK)
- luaV_finishfastset(L, upval, rc);
- else
- Protect(luaV_finishset(L, upval, rb, rc, hres));
- vmbreak;
- }
- vmcase(OP_SETTABLE) {
- StkId ra = RA(i);
- int hres;
- TValue *rb = vRB(i); /* key (table is in 'ra') */
- TValue *rc = RKC(i); /* value */
- if (ttisinteger(rb)) { /* fast track for integers? */
- luaV_fastseti(s2v(ra), ivalue(rb), rc, hres);
- }
- else {
- luaV_fastset(s2v(ra), rb, rc, hres, luaH_pset);
- }
- if (hres == HOK)
- luaV_finishfastset(L, s2v(ra), rc);
- else
- Protect(luaV_finishset(L, s2v(ra), rb, rc, hres));
- vmbreak;
- }
- vmcase(OP_SETI) {
- StkId ra = RA(i);
- int hres;
- int b = GETARG_B(i);
- TValue *rc = RKC(i);
- luaV_fastseti(s2v(ra), b, rc, hres);
- if (hres == HOK)
- luaV_finishfastset(L, s2v(ra), rc);
- else {
- TValue key;
- setivalue(&key, b);
- Protect(luaV_finishset(L, s2v(ra), &key, rc, hres));
- }
- vmbreak;
- }
- vmcase(OP_SETFIELD) {
- StkId ra = RA(i);
- int hres;
- TValue *rb = KB(i);
- TValue *rc = RKC(i);
- TString *key = tsvalue(rb); /* key must be a short string */
- luaV_fastset(s2v(ra), key, rc, hres, luaH_psetshortstr);
- if (hres == HOK)
- luaV_finishfastset(L, s2v(ra), rc);
- else
- Protect(luaV_finishset(L, s2v(ra), rb, rc, hres));
- vmbreak;
- }
- vmcase(OP_NEWTABLE) {
- StkId ra = RA(i);
- unsigned b = cast_uint(GETARG_vB(i)); /* log2(hash size) + 1 */
- unsigned c = cast_uint(GETARG_vC(i)); /* array size */
- Table *t;
- if (b > 0)
- b = 1u << (b - 1); /* hash size is 2^(b - 1) */
- if (TESTARG_k(i)) { /* non-zero extra argument? */
- lua_assert(GETARG_Ax(*pc) != 0);
- /* add it to array size */
- c += cast_uint(GETARG_Ax(*pc)) * (MAXARG_vC + 1);
- }
- pc++; /* skip extra argument */
- L->top.p = ra + 1; /* correct top in case of emergency GC */
- t = luaH_new(L); /* memory allocation */
- sethvalue2s(L, ra, t);
- if (b != 0 || c != 0)
- luaH_resize(L, t, c, b); /* idem */
- checkGC(L, ra + 1);
- vmbreak;
- }
- vmcase(OP_SELF) {
- StkId ra = RA(i);
- lu_byte tag;
- TValue *rb = vRB(i);
- TValue *rc = KC(i);
- TString *key = tsvalue(rc); /* key must be a short string */
- setobj2s(L, ra + 1, rb);
- luaV_fastget(rb, key, s2v(ra), luaH_getshortstr, tag);
- if (tagisempty(tag))
- Protect(luaV_finishget(L, rb, rc, ra, tag));
- vmbreak;
- }
- vmcase(OP_ADDI) {
- op_arithI(L, l_addi, luai_numadd);
- vmbreak;
- }
- vmcase(OP_ADDK) {
- op_arithK(L, l_addi, luai_numadd);
- vmbreak;
- }
- vmcase(OP_SUBK) {
- op_arithK(L, l_subi, luai_numsub);
- vmbreak;
- }
- vmcase(OP_MULK) {
- op_arithK(L, l_muli, luai_nummul);
- vmbreak;
- }
- vmcase(OP_MODK) {
- savestate(L, ci); /* in case of division by 0 */
- op_arithK(L, luaV_mod, luaV_modf);
- vmbreak;
- }
- vmcase(OP_POWK) {
- op_arithfK(L, luai_numpow);
- vmbreak;
- }
- vmcase(OP_DIVK) {
- op_arithfK(L, luai_numdiv);
- vmbreak;
- }
- vmcase(OP_IDIVK) {
- savestate(L, ci); /* in case of division by 0 */
- op_arithK(L, luaV_idiv, luai_numidiv);
- vmbreak;
- }
- vmcase(OP_BANDK) {
- op_bitwiseK(L, l_band);
- vmbreak;
- }
- vmcase(OP_BORK) {
- op_bitwiseK(L, l_bor);
- vmbreak;
- }
- vmcase(OP_BXORK) {
- op_bitwiseK(L, l_bxor);
- vmbreak;
- }
- vmcase(OP_SHLI) {
- StkId ra = RA(i);
- TValue *rb = vRB(i);
- int ic = GETARG_sC(i);
- lua_Integer ib;
- if (tointegerns(rb, &ib)) {
- pc++; setivalue(s2v(ra), luaV_shiftl(ic, ib));
- }
- vmbreak;
- }
- vmcase(OP_SHRI) {
- StkId ra = RA(i);
- TValue *rb = vRB(i);
- int ic = GETARG_sC(i);
- lua_Integer ib;
- if (tointegerns(rb, &ib)) {
- pc++; setivalue(s2v(ra), luaV_shiftl(ib, -ic));
- }
- vmbreak;
- }
- vmcase(OP_ADD) {
- op_arith(L, l_addi, luai_numadd);
- vmbreak;
- }
- vmcase(OP_SUB) {
- op_arith(L, l_subi, luai_numsub);
- vmbreak;
- }
- vmcase(OP_MUL) {
- op_arith(L, l_muli, luai_nummul);
- vmbreak;
- }
- vmcase(OP_MOD) {
- savestate(L, ci); /* in case of division by 0 */
- op_arith(L, luaV_mod, luaV_modf);
- vmbreak;
- }
- vmcase(OP_POW) {
- op_arithf(L, luai_numpow);
- vmbreak;
- }
- vmcase(OP_DIV) { /* float division (always with floats) */
- op_arithf(L, luai_numdiv);
- vmbreak;
- }
- vmcase(OP_IDIV) { /* floor division */
- savestate(L, ci); /* in case of division by 0 */
- op_arith(L, luaV_idiv, luai_numidiv);
- vmbreak;
- }
- vmcase(OP_BAND) {
- op_bitwise(L, l_band);
- vmbreak;
- }
- vmcase(OP_BOR) {
- op_bitwise(L, l_bor);
- vmbreak;
- }
- vmcase(OP_BXOR) {
- op_bitwise(L, l_bxor);
- vmbreak;
- }
- vmcase(OP_SHL) {
- op_bitwise(L, luaV_shiftl);
- vmbreak;
- }
- vmcase(OP_SHR) {
- op_bitwise(L, luaV_shiftr);
- vmbreak;
- }
- vmcase(OP_MMBIN) {
- StkId ra = RA(i);
- Instruction pi = *(pc - 2); /* original arith. expression */
- TValue *rb = vRB(i);
- TMS tm = (TMS)GETARG_C(i);
- StkId result = RA(pi);
- lua_assert(OP_ADD <= GET_OPCODE(pi) && GET_OPCODE(pi) <= OP_SHR);
- Protect(luaT_trybinTM(L, s2v(ra), rb, result, tm));
- vmbreak;
- }
- vmcase(OP_MMBINI) {
- StkId ra = RA(i);
- Instruction pi = *(pc - 2); /* original arith. expression */
- int imm = GETARG_sB(i);
- TMS tm = (TMS)GETARG_C(i);
- int flip = GETARG_k(i);
- StkId result = RA(pi);
- Protect(luaT_trybiniTM(L, s2v(ra), imm, flip, result, tm));
- vmbreak;
- }
- vmcase(OP_MMBINK) {
- StkId ra = RA(i);
- Instruction pi = *(pc - 2); /* original arith. expression */
- TValue *imm = KB(i);
- TMS tm = (TMS)GETARG_C(i);
- int flip = GETARG_k(i);
- StkId result = RA(pi);
- Protect(luaT_trybinassocTM(L, s2v(ra), imm, flip, result, tm));
- vmbreak;
- }
- vmcase(OP_UNM) {
- StkId ra = RA(i);
- TValue *rb = vRB(i);
- lua_Number nb;
- if (ttisinteger(rb)) {
- lua_Integer ib = ivalue(rb);
- setivalue(s2v(ra), intop(-, 0, ib));
- }
- else if (tonumberns(rb, nb)) {
- setfltvalue(s2v(ra), luai_numunm(L, nb));
- }
- else
- Protect(luaT_trybinTM(L, rb, rb, ra, TM_UNM));
- vmbreak;
- }
- vmcase(OP_BNOT) {
- StkId ra = RA(i);
- TValue *rb = vRB(i);
- lua_Integer ib;
- if (tointegerns(rb, &ib)) {
- setivalue(s2v(ra), intop(^, ~l_castS2U(0), ib));
- }
- else
- Protect(luaT_trybinTM(L, rb, rb, ra, TM_BNOT));
- vmbreak;
- }
- vmcase(OP_NOT) {
- StkId ra = RA(i);
- TValue *rb = vRB(i);
- if (l_isfalse(rb))
- setbtvalue(s2v(ra));
- else
- setbfvalue(s2v(ra));
- vmbreak;
- }
- vmcase(OP_LEN) {
- StkId ra = RA(i);
- Protect(luaV_objlen(L, ra, vRB(i)));
- vmbreak;
- }
- vmcase(OP_CONCAT) {
- StkId ra = RA(i);
- int n = GETARG_B(i); /* number of elements to concatenate */
- L->top.p = ra + n; /* mark the end of concat operands */
- ProtectNT(luaV_concat(L, n));
- checkGC(L, L->top.p); /* 'luaV_concat' ensures correct top */
- vmbreak;
- }
- vmcase(OP_CLOSE) {
- StkId ra = RA(i);
- lua_assert(!GETARG_B(i)); /* 'close must be alive */
- Protect(luaF_close(L, ra, LUA_OK, 1));
- vmbreak;
- }
- vmcase(OP_TBC) {
- StkId ra = RA(i);
- /* create new to-be-closed upvalue */
- halfProtect(luaF_newtbcupval(L, ra));
- vmbreak;
- }
- vmcase(OP_JMP) {
- dojump(ci, i, 0);
- vmbreak;
- }
- vmcase(OP_EQ) {
- StkId ra = RA(i);
- int cond;
- TValue *rb = vRB(i);
- Protect(cond = luaV_equalobj(L, s2v(ra), rb));
- docondjump();
- vmbreak;
- }
- vmcase(OP_LT) {
- op_order(L, l_lti, LTnum, lessthanothers);
- vmbreak;
- }
- vmcase(OP_LE) {
- op_order(L, l_lei, LEnum, lessequalothers);
- vmbreak;
- }
- vmcase(OP_EQK) {
- StkId ra = RA(i);
- TValue *rb = KB(i);
- /* basic types do not use '__eq'; we can use raw equality */
- int cond = luaV_rawequalobj(s2v(ra), rb);
- docondjump();
- vmbreak;
- }
- vmcase(OP_EQI) {
- StkId ra = RA(i);
- int cond;
- int im = GETARG_sB(i);
- if (ttisinteger(s2v(ra)))
- cond = (ivalue(s2v(ra)) == im);
- else if (ttisfloat(s2v(ra)))
- cond = luai_numeq(fltvalue(s2v(ra)), cast_num(im));
- else
- cond = 0; /* other types cannot be equal to a number */
- docondjump();
- vmbreak;
- }
- vmcase(OP_LTI) {
- op_orderI(L, l_lti, luai_numlt, 0, TM_LT);
- vmbreak;
- }
- vmcase(OP_LEI) {
- op_orderI(L, l_lei, luai_numle, 0, TM_LE);
- vmbreak;
- }
- vmcase(OP_GTI) {
- op_orderI(L, l_gti, luai_numgt, 1, TM_LT);
- vmbreak;
- }
- vmcase(OP_GEI) {
- op_orderI(L, l_gei, luai_numge, 1, TM_LE);
- vmbreak;
- }
- vmcase(OP_TEST) {
- StkId ra = RA(i);
- int cond = !l_isfalse(s2v(ra));
- docondjump();
- vmbreak;
- }
- vmcase(OP_TESTSET) {
- StkId ra = RA(i);
- TValue *rb = vRB(i);
- if (l_isfalse(rb) == GETARG_k(i))
- pc++;
- else {
- setobj2s(L, ra, rb);
- donextjump(ci);
- }
- vmbreak;
- }
- vmcase(OP_CALL) {
- StkId ra = RA(i);
- CallInfo *newci;
- int b = GETARG_B(i);
- int nresults = GETARG_C(i) - 1;
- if (b != 0) /* fixed number of arguments? */
- L->top.p = ra + b; /* top signals number of arguments */
- /* else previous instruction set top */
- savepc(ci); /* in case of errors */
- if ((newci = luaD_precall(L, ra, nresults)) == NULL)
- updatetrap(ci); /* C call; nothing else to be done */
- else { /* Lua call: run function in this same C frame */
- ci = newci;
- goto startfunc;
- }
- vmbreak;
- }
- vmcase(OP_TAILCALL) {
- StkId ra = RA(i);
- int b = GETARG_B(i); /* number of arguments + 1 (function) */
- int n; /* number of results when calling a C function */
- int nparams1 = GETARG_C(i);
- /* delta is virtual 'func' - real 'func' (vararg functions) */
- int delta = (nparams1) ? ci->u.l.nextraargs + nparams1 : 0;
- if (b != 0)
- L->top.p = ra + b;
- else /* previous instruction set top */
- b = cast_int(L->top.p - ra);
- savepc(ci); /* several calls here can raise errors */
- if (TESTARG_k(i)) {
- luaF_closeupval(L, base); /* close upvalues from current call */
- lua_assert(L->tbclist.p < base); /* no pending tbc variables */
- lua_assert(base == ci->func.p + 1);
- }
- if ((n = luaD_pretailcall(L, ci, ra, b, delta)) < 0) /* Lua function? */
- goto startfunc; /* execute the callee */
- else { /* C function? */
- ci->func.p -= delta; /* restore 'func' (if vararg) */
- luaD_poscall(L, ci, n); /* finish caller */
- updatetrap(ci); /* 'luaD_poscall' can change hooks */
- goto ret; /* caller returns after the tail call */
- }
- }
- vmcase(OP_RETURN) {
- StkId ra = RA(i);
- int n = GETARG_B(i) - 1; /* number of results */
- int nparams1 = GETARG_C(i);
- if (n < 0) /* not fixed? */
- n = cast_int(L->top.p - ra); /* get what is available */
- savepc(ci);
- if (TESTARG_k(i)) { /* may there be open upvalues? */
- ci->u2.nres = n; /* save number of returns */
- if (L->top.p < ci->top.p)
- L->top.p = ci->top.p;
- luaF_close(L, base, CLOSEKTOP, 1);
- updatetrap(ci);
- updatestack(ci);
- }
- if (nparams1) /* vararg function? */
- ci->func.p -= ci->u.l.nextraargs + nparams1;
- L->top.p = ra + n; /* set call for 'luaD_poscall' */
- luaD_poscall(L, ci, n);
- updatetrap(ci); /* 'luaD_poscall' can change hooks */
- goto ret;
- }
- vmcase(OP_RETURN0) {
- if (l_unlikely(L->hookmask)) {
- StkId ra = RA(i);
- L->top.p = ra;
- savepc(ci);
- luaD_poscall(L, ci, 0); /* no hurry... */
- trap = 1;
- }
- else { /* do the 'poscall' here */
- int nres = get_nresults(ci->callstatus);
- L->ci = ci->previous; /* back to caller */
- L->top.p = base - 1;
- for (; l_unlikely(nres > 0); nres--)
- setnilvalue(s2v(L->top.p++)); /* all results are nil */
- }
- goto ret;
- }
- vmcase(OP_RETURN1) {
- if (l_unlikely(L->hookmask)) {
- StkId ra = RA(i);
- L->top.p = ra + 1;
- savepc(ci);
- luaD_poscall(L, ci, 1); /* no hurry... */
- trap = 1;
- }
- else { /* do the 'poscall' here */
- int nres = get_nresults(ci->callstatus);
- L->ci = ci->previous; /* back to caller */
- if (nres == 0)
- L->top.p = base - 1; /* asked for no results */
- else {
- StkId ra = RA(i);
- setobjs2s(L, base - 1, ra); /* at least this result */
- L->top.p = base;
- for (; l_unlikely(nres > 1); nres--)
- setnilvalue(s2v(L->top.p++)); /* complete missing results */
- }
- }
- ret: /* return from a Lua function */
- if (ci->callstatus & CIST_FRESH)
- return; /* end this frame */
- else {
- ci = ci->previous;
- goto returning; /* continue running caller in this frame */
- }
- }
- vmcase(OP_FORLOOP) {
- StkId ra = RA(i);
- if (ttisinteger(s2v(ra + 1))) { /* integer loop? */
- lua_Unsigned count = l_castS2U(ivalue(s2v(ra)));
- if (count > 0) { /* still more iterations? */
- lua_Integer step = ivalue(s2v(ra + 1));
- lua_Integer idx = ivalue(s2v(ra + 2)); /* control variable */
- chgivalue(s2v(ra), l_castU2S(count - 1)); /* update counter */
- idx = intop(+, idx, step); /* add step to index */
- chgivalue(s2v(ra + 2), idx); /* update control variable */
- pc -= GETARG_Bx(i); /* jump back */
- }
- }
- else if (floatforloop(L, ra)) /* float loop */
- pc -= GETARG_Bx(i); /* jump back */
- updatetrap(ci); /* allows a signal to break the loop */
- vmbreak;
- }
- vmcase(OP_FORPREP) {
- StkId ra = RA(i);
- savestate(L, ci); /* in case of errors */
- if (forprep(L, ra))
- pc += GETARG_Bx(i) + 1; /* skip the loop */
- vmbreak;
- }
- vmcase(OP_TFORPREP) {
- /* before: 'ra' has the iterator function, 'ra + 1' has the state,
- 'ra + 2' has the initial value for the control variable, and
- 'ra + 3' has the closing variable. This opcode then swaps the
- control and the closing variables and marks the closing variable
- as to-be-closed.
- */
- StkId ra = RA(i);
- TValue temp; /* to swap control and closing variables */
- setobj(L, &temp, s2v(ra + 3));
- setobjs2s(L, ra + 3, ra + 2);
- setobj2s(L, ra + 2, &temp);
- /* create to-be-closed upvalue (if closing var. is not nil) */
- halfProtect(luaF_newtbcupval(L, ra + 2));
- pc += GETARG_Bx(i); /* go to end of the loop */
- i = *(pc++); /* fetch next instruction */
- lua_assert(GET_OPCODE(i) == OP_TFORCALL && ra == RA(i));
- goto l_tforcall;
- }
- vmcase(OP_TFORCALL) {
- l_tforcall: {
- /* 'ra' has the iterator function, 'ra + 1' has the state,
- 'ra + 2' has the closing variable, and 'ra + 3' has the control
- variable. The call will use the stack starting at 'ra + 3',
- so that it preserves the first three values, and the first
- return will be the new value for the control variable.
- */
- StkId ra = RA(i);
- setobjs2s(L, ra + 5, ra + 3); /* copy the control variable */
- setobjs2s(L, ra + 4, ra + 1); /* copy state */
- setobjs2s(L, ra + 3, ra); /* copy function */
- L->top.p = ra + 3 + 3;
- ProtectNT(luaD_call(L, ra + 3, GETARG_C(i))); /* do the call */
- updatestack(ci); /* stack may have changed */
- i = *(pc++); /* go to next instruction */
- lua_assert(GET_OPCODE(i) == OP_TFORLOOP && ra == RA(i));
- goto l_tforloop;
- }}
- vmcase(OP_TFORLOOP) {
- l_tforloop: {
- StkId ra = RA(i);
- if (!ttisnil(s2v(ra + 3))) /* continue loop? */
- pc -= GETARG_Bx(i); /* jump back */
- vmbreak;
- }}
- vmcase(OP_SETLIST) {
- StkId ra = RA(i);
- unsigned n = cast_uint(GETARG_vB(i));
- unsigned last = cast_uint(GETARG_vC(i));
- Table *h = hvalue(s2v(ra));
- if (n == 0)
- n = cast_uint(L->top.p - ra) - 1; /* get up to the top */
- else
- L->top.p = ci->top.p; /* correct top in case of emergency GC */
- last += n;
- if (TESTARG_k(i)) {
- last += cast_uint(GETARG_Ax(*pc)) * (MAXARG_vC + 1);
- pc++;
- }
- /* when 'n' is known, table should have proper size */
- if (last > h->asize) { /* needs more space? */
- /* fixed-size sets should have space preallocated */
- lua_assert(GETARG_vB(i) == 0);
- luaH_resizearray(L, h, last); /* preallocate it at once */
- }
- for (; n > 0; n--) {
- TValue *val = s2v(ra + n);
- obj2arr(h, last - 1, val);
- last--;
- luaC_barrierback(L, obj2gco(h), val);
- }
- vmbreak;
- }
- vmcase(OP_CLOSURE) {
- StkId ra = RA(i);
- Proto *p = cl->p->p[GETARG_Bx(i)];
- halfProtect(pushclosure(L, p, cl->upvals, base, ra));
- checkGC(L, ra + 1);
- vmbreak;
- }
- vmcase(OP_VARARG) {
- StkId ra = RA(i);
- int n = GETARG_C(i) - 1; /* required results (-1 means all) */
- int vatab = GETARG_k(i) ? GETARG_B(i) : -1;
- Protect(luaT_getvarargs(L, ci, ra, n, vatab));
- vmbreak;
- }
- vmcase(OP_GETVARG) {
- StkId ra = RA(i);
- TValue *rc = vRC(i);
- luaT_getvararg(ci, ra, rc);
- vmbreak;
- }
- vmcase(OP_ERRNNIL) {
- TValue *ra = vRA(i);
- if (!ttisnil(ra))
- halfProtect(luaG_errnnil(L, cl, GETARG_Bx(i)));
- vmbreak;
- }
- vmcase(OP_VARARGPREP) {
- ProtectNT(luaT_adjustvarargs(L, ci, cl->p));
- if (l_unlikely(trap)) { /* previous "Protect" updated trap */
- luaD_hookcall(L, ci);
- L->oldpc = 1; /* next opcode will be seen as a "new" line */
- }
- updatebase(ci); /* function has new base after adjustment */
- vmbreak;
- }
- vmcase(OP_EXTRAARG) {
- lua_assert(0);
- vmbreak;
- }
- }
- }
-}
-
-/* }================================================================== */
diff --git a/lvm.h b/lvm.h
deleted file mode 100644
index be7b9cb0ea..0000000000
--- a/lvm.h
+++ /dev/null
@@ -1,136 +0,0 @@
-/*
-** $Id: lvm.h $
-** Lua virtual machine
-** See Copyright Notice in lua.h
-*/
-
-#ifndef lvm_h
-#define lvm_h
-
-
-#include "ldo.h"
-#include "lobject.h"
-#include "ltm.h"
-
-
-#if !defined(LUA_NOCVTN2S)
-#define cvt2str(o) ttisnumber(o)
-#else
-#define cvt2str(o) 0 /* no conversion from numbers to strings */
-#endif
-
-
-#if !defined(LUA_NOCVTS2N)
-#define cvt2num(o) ttisstring(o)
-#else
-#define cvt2num(o) 0 /* no conversion from strings to numbers */
-#endif
-
-
-/*
-** You can define LUA_FLOORN2I if you want to convert floats to integers
-** by flooring them (instead of raising an error if they are not
-** integral values)
-*/
-#if !defined(LUA_FLOORN2I)
-#define LUA_FLOORN2I F2Ieq
-#endif
-
-
-/*
-** Rounding modes for float->integer coercion
- */
-typedef enum {
- F2Ieq, /* no rounding; accepts only integral values */
- F2Ifloor, /* takes the floor of the number */
- F2Iceil /* takes the ceiling of the number */
-} F2Imod;
-
-
-/* convert an object to a float (including string coercion) */
-#define tonumber(o,n) \
- (ttisfloat(o) ? (*(n) = fltvalue(o), 1) : luaV_tonumber_(o,n))
-
-
-/* convert an object to a float (without string coercion) */
-#define tonumberns(o,n) \
- (ttisfloat(o) ? ((n) = fltvalue(o), 1) : \
- (ttisinteger(o) ? ((n) = cast_num(ivalue(o)), 1) : 0))
-
-
-/* convert an object to an integer (including string coercion) */
-#define tointeger(o,i) \
- (l_likely(ttisinteger(o)) ? (*(i) = ivalue(o), 1) \
- : luaV_tointeger(o,i,LUA_FLOORN2I))
-
-
-/* convert an object to an integer (without string coercion) */
-#define tointegerns(o,i) \
- (l_likely(ttisinteger(o)) ? (*(i) = ivalue(o), 1) \
- : luaV_tointegerns(o,i,LUA_FLOORN2I))
-
-
-#define intop(op,v1,v2) l_castU2S(l_castS2U(v1) op l_castS2U(v2))
-
-#define luaV_rawequalobj(t1,t2) luaV_equalobj(NULL,t1,t2)
-
-
-/*
-** fast track for 'gettable'
-*/
-#define luaV_fastget(t,k,res,f, tag) \
- (tag = (!ttistable(t) ? LUA_VNOTABLE : f(hvalue(t), k, res)))
-
-
-/*
-** Special case of 'luaV_fastget' for integers, inlining the fast case
-** of 'luaH_getint'.
-*/
-#define luaV_fastgeti(t,k,res,tag) \
- if (!ttistable(t)) tag = LUA_VNOTABLE; \
- else { luaH_fastgeti(hvalue(t), k, res, tag); }
-
-
-#define luaV_fastset(t,k,val,hres,f) \
- (hres = (!ttistable(t) ? HNOTATABLE : f(hvalue(t), k, val)))
-
-#define luaV_fastseti(t,k,val,hres) \
- if (!ttistable(t)) hres = HNOTATABLE; \
- else { luaH_fastseti(hvalue(t), k, val, hres); }
-
-
-/*
-** Finish a fast set operation (when fast set succeeds).
-*/
-#define luaV_finishfastset(L,t,v) luaC_barrierback(L, gcvalue(t), v)
-
-
-/*
-** Shift right is the same as shift left with a negative 'y'
-*/
-#define luaV_shiftr(x,y) luaV_shiftl(x,intop(-, 0, y))
-
-
-
-LUAI_FUNC int luaV_equalobj (lua_State *L, const TValue *t1, const TValue *t2);
-LUAI_FUNC int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r);
-LUAI_FUNC int luaV_lessequal (lua_State *L, const TValue *l, const TValue *r);
-LUAI_FUNC int luaV_tonumber_ (const TValue *obj, lua_Number *n);
-LUAI_FUNC int luaV_tointeger (const TValue *obj, lua_Integer *p, F2Imod mode);
-LUAI_FUNC int luaV_tointegerns (const TValue *obj, lua_Integer *p,
- F2Imod mode);
-LUAI_FUNC int luaV_flttointeger (lua_Number n, lua_Integer *p, F2Imod mode);
-LUAI_FUNC lu_byte luaV_finishget (lua_State *L, const TValue *t, TValue *key,
- StkId val, lu_byte tag);
-LUAI_FUNC void luaV_finishset (lua_State *L, const TValue *t, TValue *key,
- TValue *val, int aux);
-LUAI_FUNC void luaV_finishOp (lua_State *L);
-LUAI_FUNC void luaV_execute (lua_State *L, CallInfo *ci);
-LUAI_FUNC void luaV_concat (lua_State *L, int total);
-LUAI_FUNC lua_Integer luaV_idiv (lua_State *L, lua_Integer x, lua_Integer y);
-LUAI_FUNC lua_Integer luaV_mod (lua_State *L, lua_Integer x, lua_Integer y);
-LUAI_FUNC lua_Number luaV_modf (lua_State *L, lua_Number x, lua_Number y);
-LUAI_FUNC lua_Integer luaV_shiftl (lua_Integer x, lua_Integer y);
-LUAI_FUNC void luaV_objlen (lua_State *L, StkId ra, const TValue *rb);
-
-#endif
diff --git a/makefile b/makefile
deleted file mode 100644
index fa165bca6a..0000000000
--- a/makefile
+++ /dev/null
@@ -1,219 +0,0 @@
-# Developer's makefile for building Lua
-# see luaconf.h for further customization
-
-# == CHANGE THE SETTINGS BELOW TO SUIT YOUR ENVIRONMENT =======================
-
-# Warnings valid for both C and C++
-CWARNSCPP= \
- -Wfatal-errors \
- -Wextra \
- -Wshadow \
- -Wundef \
- -Wwrite-strings \
- -Wredundant-decls \
- -Wdisabled-optimization \
- -Wdouble-promotion \
- -Wmissing-declarations \
- -Wconversion \
- # the next warnings might be useful sometimes,
- # but usually they generate too much noise
- # -Wstrict-overflow=2 \
- # -Werror \
- # -pedantic # warns if we use jump tables \
- # -Wformat=2 \
- # -Wcast-qual \
-
-
-# Warnings for gcc, not valid for clang
-CWARNGCC= \
- -Wlogical-op \
- -Wno-aggressive-loop-optimizations \
-
-
-# The next warnings are neither valid nor needed for C++
-CWARNSC= -Wdeclaration-after-statement \
- -Wmissing-prototypes \
- -Wnested-externs \
- -Wstrict-prototypes \
- -Wc++-compat \
- -Wold-style-definition \
-
-
-CWARNS= $(CWARNSCPP) $(CWARNSC) $(CWARNGCC)
-
-# Some useful compiler options for internal tests:
-# -DLUAI_ASSERT turns on all assertions inside Lua.
-# -DHARDSTACKTESTS forces a reallocation of the stack at every point where
-# the stack can be reallocated.
-# -DHARDMEMTESTS forces a full collection at all points where the collector
-# can run.
-# -DEMERGENCYGCTESTS forces an emergency collection at every single allocation.
-# -DEXTERNMEMCHECK removes internal consistency checking of blocks being
-# deallocated (useful when an external tool like valgrind does the check).
-# -DMAXINDEXRK=k limits range of constants in RK instruction operands.
-# -DLUA_COMPAT_5_3
-
-# -pg -malign-double
-# -DLUA_USE_CTYPE -DLUA_USE_APICHECK
-
-# The following options help detect "undefined behavior"s that seldom
-# create problems; some are only available in newer gcc versions. To
-# use some of them, we also have to define an environment variable
-# ASAN_OPTIONS="detect_invalid_pointer_pairs=2".
-# -fsanitize=undefined (you may need to add "-lubsan" to libs)
-# -fsanitize=pointer-subtract -fsanitize=address -fsanitize=pointer-compare
-# TESTS= -DLUA_USER_H='"ltests.h"' -Og -g
-
-
-LOCAL = $(TESTS) $(CWARNS)
-
-
-# To enable Linux goodies, -DLUA_USE_LINUX
-# For C89, "-std=c89 -DLUA_USE_C89"
-# Note that Linux/Posix options are not compatible with C89
-MYCFLAGS= $(LOCAL) -std=c99 -DLUA_USE_LINUX
-MYLDFLAGS= -Wl,-E
-MYLIBS= -ldl
-
-
-CC= gcc
-CFLAGS= -Wall -O2 $(MYCFLAGS) -fno-stack-protector -fno-common -march=native
-AR= ar rc
-RANLIB= ranlib
-RM= rm -f
-
-
-
-# == END OF USER SETTINGS. NO NEED TO CHANGE ANYTHING BELOW THIS LINE =========
-
-
-LIBS = -lm
-
-CORE_T= liblua.a
-CORE_O= lapi.o lcode.o lctype.o ldebug.o ldo.o ldump.o lfunc.o lgc.o llex.o \
- lmem.o lobject.o lopcodes.o lparser.o lstate.o lstring.o ltable.o \
- ltm.o lundump.o lvm.o lzio.o ltests.o
-AUX_O= lauxlib.o
-LIB_O= lbaselib.o ldblib.o liolib.o lmathlib.o loslib.o ltablib.o lstrlib.o \
- lutf8lib.o loadlib.o lcorolib.o linit.o
-
-LUA_T= lua
-LUA_O= lua.o
-
-
-ALL_T= $(CORE_T) $(LUA_T)
-ALL_O= $(CORE_O) $(LUA_O) $(AUX_O) $(LIB_O)
-ALL_A= $(CORE_T)
-
-all: $(ALL_T)
- touch all
-
-o: $(ALL_O)
-
-a: $(ALL_A)
-
-$(CORE_T): $(CORE_O) $(AUX_O) $(LIB_O)
- $(AR) $@ $?
- $(RANLIB) $@
-
-$(LUA_T): $(LUA_O) $(CORE_T)
- $(CC) -o $@ $(MYLDFLAGS) $(LUA_O) $(CORE_T) $(LIBS) $(MYLIBS) $(DL)
-
-
-clean:
- $(RM) $(ALL_T) $(ALL_O)
-
-depend:
- @$(CC) $(CFLAGS) -MM *.c
-
-echo:
- @echo "CC = $(CC)"
- @echo "CFLAGS = $(CFLAGS)"
- @echo "AR = $(AR)"
- @echo "RANLIB = $(RANLIB)"
- @echo "RM = $(RM)"
- @echo "MYCFLAGS = $(MYCFLAGS)"
- @echo "MYLDFLAGS = $(MYLDFLAGS)"
- @echo "MYLIBS = $(MYLIBS)"
- @echo "DL = $(DL)"
-
-$(ALL_O): makefile ltests.h
-
-# DO NOT EDIT
-# automatically made with 'gcc -MM l*.c'
-
-lapi.o: lapi.c lprefix.h lua.h luaconf.h lapi.h llimits.h lstate.h \
- lobject.h ltm.h lzio.h lmem.h ldebug.h ldo.h lfunc.h lgc.h lstring.h \
- ltable.h lundump.h lvm.h
-lauxlib.o: lauxlib.c lprefix.h lua.h luaconf.h lauxlib.h llimits.h
-lbaselib.o: lbaselib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h \
- llimits.h
-lcode.o: lcode.c lprefix.h lua.h luaconf.h lcode.h llex.h lobject.h \
- llimits.h lzio.h lmem.h lopcodes.h lparser.h ldebug.h lstate.h ltm.h \
- ldo.h lgc.h lstring.h ltable.h lvm.h lopnames.h
-lcorolib.o: lcorolib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h \
- llimits.h
-lctype.o: lctype.c lprefix.h lctype.h lua.h luaconf.h llimits.h
-ldblib.o: ldblib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h llimits.h
-ldebug.o: ldebug.c lprefix.h lua.h luaconf.h lapi.h llimits.h lstate.h \
- lobject.h ltm.h lzio.h lmem.h lcode.h llex.h lopcodes.h lparser.h \
- ldebug.h ldo.h lfunc.h lstring.h lgc.h ltable.h lvm.h
-ldo.o: ldo.c lprefix.h lua.h luaconf.h lapi.h llimits.h lstate.h \
- lobject.h ltm.h lzio.h lmem.h ldebug.h ldo.h lfunc.h lgc.h lopcodes.h \
- lparser.h lstring.h ltable.h lundump.h lvm.h
-ldump.o: ldump.c lprefix.h lua.h luaconf.h lapi.h llimits.h lstate.h \
- lobject.h ltm.h lzio.h lmem.h lgc.h ltable.h lundump.h
-lfunc.o: lfunc.c lprefix.h lua.h luaconf.h ldebug.h lstate.h lobject.h \
- llimits.h ltm.h lzio.h lmem.h ldo.h lfunc.h lgc.h
-lgc.o: lgc.c lprefix.h lua.h luaconf.h ldebug.h lstate.h lobject.h \
- llimits.h ltm.h lzio.h lmem.h ldo.h lfunc.h lgc.h lstring.h ltable.h
-linit.o: linit.c lprefix.h lua.h luaconf.h lualib.h lauxlib.h llimits.h
-liolib.o: liolib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h llimits.h
-llex.o: llex.c lprefix.h lua.h luaconf.h lctype.h llimits.h ldebug.h \
- lstate.h lobject.h ltm.h lzio.h lmem.h ldo.h lgc.h llex.h lparser.h \
- lstring.h ltable.h
-lmathlib.o: lmathlib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h \
- llimits.h
-lmem.o: lmem.c lprefix.h lua.h luaconf.h ldebug.h lstate.h lobject.h \
- llimits.h ltm.h lzio.h lmem.h ldo.h lgc.h
-loadlib.o: loadlib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h \
- llimits.h
-lobject.o: lobject.c lprefix.h lua.h luaconf.h lctype.h llimits.h \
- ldebug.h lstate.h lobject.h ltm.h lzio.h lmem.h ldo.h lstring.h lgc.h \
- lvm.h
-lopcodes.o: lopcodes.c lprefix.h lopcodes.h llimits.h lua.h luaconf.h \
- lobject.h
-loslib.o: loslib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h llimits.h
-lparser.o: lparser.c lprefix.h lua.h luaconf.h lcode.h llex.h lobject.h \
- llimits.h lzio.h lmem.h lopcodes.h lparser.h ldebug.h lstate.h ltm.h \
- ldo.h lfunc.h lstring.h lgc.h ltable.h
-lstate.o: lstate.c lprefix.h lua.h luaconf.h lapi.h llimits.h lstate.h \
- lobject.h ltm.h lzio.h lmem.h ldebug.h ldo.h lfunc.h lgc.h llex.h \
- lstring.h ltable.h
-lstring.o: lstring.c lprefix.h lua.h luaconf.h ldebug.h lstate.h \
- lobject.h llimits.h ltm.h lzio.h lmem.h ldo.h lstring.h lgc.h
-lstrlib.o: lstrlib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h \
- llimits.h
-ltable.o: ltable.c lprefix.h lua.h luaconf.h ldebug.h lstate.h lobject.h \
- llimits.h ltm.h lzio.h lmem.h ldo.h lgc.h lstring.h ltable.h lvm.h
-ltablib.o: ltablib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h \
- llimits.h
-ltests.o: ltests.c lprefix.h lua.h luaconf.h lapi.h llimits.h lstate.h \
- lobject.h ltm.h lzio.h lmem.h lauxlib.h lcode.h llex.h lopcodes.h \
- lparser.h lctype.h ldebug.h ldo.h lfunc.h lopnames.h lstring.h lgc.h \
- ltable.h lualib.h
-ltm.o: ltm.c lprefix.h lua.h luaconf.h ldebug.h lstate.h lobject.h \
- llimits.h ltm.h lzio.h lmem.h ldo.h lgc.h lstring.h ltable.h lvm.h
-lua.o: lua.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h llimits.h
-lundump.o: lundump.c lprefix.h lua.h luaconf.h ldebug.h lstate.h \
- lobject.h llimits.h ltm.h lzio.h lmem.h ldo.h lfunc.h lstring.h lgc.h \
- ltable.h lundump.h
-lutf8lib.o: lutf8lib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h \
- llimits.h
-lvm.o: lvm.c lprefix.h lua.h luaconf.h lapi.h llimits.h lstate.h \
- lobject.h ltm.h lzio.h lmem.h ldebug.h ldo.h lfunc.h lgc.h lopcodes.h \
- lstring.h ltable.h lvm.h ljumptab.h
-lzio.o: lzio.c lprefix.h lua.h luaconf.h lapi.h llimits.h lstate.h \
- lobject.h ltm.h lzio.h lmem.h
-
-# (end of Makefile)
diff --git a/manual/2html b/manual/2html
deleted file mode 100755
index d3b88b349b..0000000000
--- a/manual/2html
+++ /dev/null
@@ -1,519 +0,0 @@
-#!/usr/bin/env lua5.3
-
-
--- special marks:
--- \1 - paragraph (empty line)
--- \4 - remove spaces around it
--- \3 - ref (followed by label|)
-
----------------------------------------------------------------
-header = [[
-
-
-
-
-Lua 5.5 Reference Manual
-
-
-
-
-
-
-
-
-
Tradução: Sérgio Queiroz de Medeiros", 1)
- header = string.gsub(header, "Lua (%d+.%d+) Reference Manual",
- "Manual de Referência de Lua %1")
- header = string.gsub(header, "All rights reserved",
- "Todos os direitos reservados")
-end
-
-
----------------------------------------------------------------
-
-local function compose (f,g)
- assert(f and g)
- return function (s) return g(f(s)) end
-end
-
-local function concat (f, g)
- assert(f and g)
- return function (s) return f(s) .. g(s) end
-end
-
-
-local Tag = {}
-
-
-setmetatable(Tag, {
- __index = function (t, tag)
- local v = function (n, att)
- local e = ""
- if type(att) == "table" then
- for k,v in pairs(att) do e = string.format('%s %s="%s"', e, k, v) end
- end
- if n then
- return string.format("<%s%s>%s%s>", tag, e, n, tag)
- else
- return string.format("<%s%s>", tag, e)
- end
- end
- t[tag] = v
- return v
- end
-})
-
-
-
----------------------------------------------------------------
-local labels = {}
-
-
-local function anchor (text, label, link, textlink)
- if labels[label] then
- error("label " .. label .. " already defined")
- end
- labels[label] = {text = textlink, link = link}
- return Tag.a(text, {name=link})
-end
-
-local function makeref (label)
- assert(not string.find(label, "|"))
- return string.format("\3%s\3", label)
-end
-
-local function ref (label)
- local l = labels[label]
- if not l then
- io.stderr:write("label ", label, " undefined\n")
- return "@@@@@@@"
- else
- return Tag.a(l.text, {href="#"..l.link})
- end
-end
-
----------------------------------------------------------------
-local function nopara (t)
- t = string.gsub(t, "\1", "\n\n")
- t = string.gsub(t, "
%s*
", "")
- return t
-end
-
-local function fixpara (t)
- t = string.gsub(t, "\1", "\n
\n\n
\n")
- t = string.gsub(t, "
%s*
", "")
- return t
-end
-
-local function antipara (t)
- return "\n" .. t .. "
"
-end
-
-
-Tag.pre = compose(Tag.pre, antipara)
-Tag.ul = compose(Tag.ul, antipara)
-
----------------------------------------------------------------
-local Gfoots = 0
-local footnotes = {}
-
-local line = Tag.hr(nil)
-
-local function dischargefoots ()
- if #footnotes == 0 then return "" end
- local fn = table.concat(footnotes)
- footnotes = {}
- return line .. Tag.h3"footnotes:" .. fn .. line
-end
-
-
-local Glists = 0
-local listings = {}
-
-local function dischargelist ()
- if #listings == 0 then return "" end
- local l = listings
- listings = {}
- return line .. table.concat(l, line..line) .. line
-end
-
----------------------------------------------------------------
-local counters = {
-h1 = {val = 1},
-h2 = {father = "h1", val = 1},
-h3 = {father = "h2", val = 1},
-listing = {father = "h1", val = 1},
-}
-
-local function inccounter (count)
- counters[count].val = counters[count].val + 1
- for c, v in pairs(counters) do
- if v.father == count then v.val = 1 end
- end
-end
-
-local function getcounter (count)
- local c = counters[count]
- if c.father then
- return getcounter(c.father) .. "." .. c.val
- else
- return c.val .. ""
- end
-end
----------------------------------------------------------------
-
-
-local function fixed (x)
- return function () return x end
-end
-
-local function id (x) return x end
-
-
-local function prepos (x, y)
- assert(x and y)
- return function (s) return string.format("%s%s%s", x, s, y) end
-end
-
-
-local rw = Tag.b
-
-
-
-
-local function LuaName (name)
- return Tag.code(name)
-end
-
-
-local function getparam (s)
- local i, e = string.find(s, "^[^%s@|]+|")
- if not i then return nil, s
- else return string.sub(s, i, e - 1), string.sub(s, e + 1)
- end
-end
-
-
-local function gettitle (h)
- local title, p = assert(string.match(h, "
(.-)()"))
- return title, string.sub(h, p)
-end
-
-local function getparamtitle (what, h, nonum)
- local label, title, c, count
- label, h = getparam(h)
- title, h = gettitle(h)
- if not nonum then
- count = getcounter(what)
- inccounter(what)
- c = string.format("%s – ", count)
- else
- c = ""
- end
- label = label or count
- if label then
- title = anchor(title, label, count, "§"..count)
- end
- title = string.format("%s%s", c, title)
- return title, h
-end
-
-local function section (what, nonum)
- return function (h)
- local title
- title, h = getparamtitle(what, h, nonum)
- local fn = what == "h1" and dischargefoots() or ""
- h = fixpara(Tag.p(h))
- return "\n" .. Tag[what](title) .. h .. fn ..
- dischargelist() .. "
"
- end
-end
-
-
-local function verbatim (s)
- s = nopara(s)
- s = string.gsub(s, "\n", "\n ")
- s = string.gsub(s, "\n%s*$", "\n")
- return Tag.pre(s)
-end
-
-
-local function verb (s)
- return Tag.code(s)
-end
-
-
-local function lua2link (e)
- return string.find(e, "luaL?_") and e or "pdf-"..e
-end
-
-
-local verbfixed = verb
-
-
-local Tex = {
-
-ANSI = function (func)
- return "ISO C function " .. Tag.code(func)
- end,
-At = fixed"@",
-B = Tag.b,
-bigskip = fixed"",
-bignum = id,
-C = fixed"",
-Ci = prepos(""),
-CId = function (func)
- return "C function " .. Tag.code(func)
- end,
-chapter = section"h1",
-Char = compose(verbfixed, prepos("'", "'")),
-Cdots = fixed"···",
-Close = fixed"}",
-col = Tag.td,
-defid = function (name)
- local l = lua2link(name)
- local c = Tag.code(name)
- return anchor(c, l, l, c)
- end,
-def = Tag.em,
-description = compose(nopara, Tag.ul),
-Em = fixed("\4" .. "—" .. "\4"),
-emph = Tag.em,
-emphx = Tag.em, -- emphasis plus index (if there was an index)
-En = fixed("–"),
-format = fixed"",
-["false"] = fixed(Tag.b"false"),
-id = Tag.code,
-idx = Tag.code,
-index = fixed"",
-Lidx = fixed"", -- Tag.code,
-ldots = fixed"...",
-x = id,
-itemize = compose(nopara, Tag.ul),
-leq = fixed"≤",
-Lid = function (s)
- return makeref(lua2link(s))
- end,
-M = Tag.em,
-N = function (s) return (string.gsub(s, " ", " ")) end,
-NE = id, -- tag"foreignphrase",
-num = id,
-["nil"] = fixed(Tag.b"nil"),
-fail = fixed(Tag.b"fail"),
-Open = fixed"{",
-part = section("h1", true),
-Pat = compose(verbfixed, prepos("'", "'")),
-preface = section("h1", true),
-psect = section("h2", true),
-Q = prepos('"', '"'),
-refchp = makeref,
-refcode = makeref,
-refsec = makeref,
-
-pi = fixed"π",
-rep = Tag.em, -- compose(prepos("<", ">"), Tag.em),
-Rw = rw,
-rw = rw,
-sb = Tag.sub,
-sp = Tag.sup,
-St = compose(verbfixed, prepos('"', '"')),
-sect1 = section"h1",
-sect2 = section"h2",
-sect3 = section"h3",
-sect4 = section("h4", true),
-simplesect = id,
-Tab2 = function (s) return Tag.table(s, {border=1}) end,
-row = Tag.tr,
-title = Tag.title,
-todo = Tag.todo,
-["true"] = fixed(Tag.b"true"),
-T = verb,
-
-item = function (s)
- local t, p = string.match(s, "^([^\n|]+)|()")
- if t then
- s = string.sub(s, p)
- s = Tag.b(t) ..": " .. s
- end
- return Tag.li(fixpara(s))
- end,
-
-verbatim = verbatim,
-
-manual = id,
-
-
--- for the manual
-
-link =function (s)
- local l, t = getparam(s)
- assert(l)
- return string.format("%s (%s)", t, makeref(l))
-end,
-
-see = function (s) return string.format(seefmt, makeref(s)) end,
-See = makeref,
-seeC = function (s)
- return string.format(seefmt, makeref(s))
- end,
-
-seeF = function (s)
- return string.format(seefmt, makeref(lua2link(s)))
- end,
-
-APIEntry = function (e)
- local h, name
- h, e = string.match(e, "^%s*(.-)%s*|(.*)$")
- name = string.match(h, "(luaL?_[%w_]+)%)? +%(") or
- string.match(h, "luaL?_[%w_]+")
- local a = anchor(Tag.code(name), name, name, Tag.code(name))
- local apiicmd, ne = string.match(e, "^(.-)(.*)")
---io.stderr:write(e)
- if not apiicmd then
- return antipara(Tag.hr() .. Tag.h3(a)) .. Tag.pre(h) .. e
- else
- return antipara(Tag.hr() .. Tag.h3(a)) .. apiicmd .. Tag.pre(h) .. ne
- end
-end,
-
-LibEntry = function (e)
- local h, name
- h, e = string.match(e, "^(.-)|(.*)$")
- name = string.gsub(h, " (.+", "")
- local l = lua2link(name)
- local a = anchor(Tag.code(h), l, l, Tag.code(name))
- return Tag.hr() .. Tag.h3(a) .. e
-end,
-
-Produc = compose(nopara, Tag.pre),
-producname = prepos("\t", " ::= "),
-Or = fixed" | ",
-VerBar = fixed"|", -- vertical bar
-OrNL = fixed" | \4",
-bnfNter = prepos("", ""),
-bnfopt = prepos("[", "]"),
-bnfrep = prepos("{", "}"),
-bnfter = compose(Tag.b, prepos("‘", "’")),
-producbody = function (s)
- s = string.gsub(s, "%s+", " ")
- s = string.gsub(s, "\4", "\n\t\t")
- return s
- end,
-
-apii = function (s)
- local pop,push,err = string.match(s, "^(.-),(.-),(.*)$")
- if pop ~= "?" and string.find(pop, "%W") then
- pop = "(" .. pop .. ")"
- end
- if push ~= "?" and string.find(push, "%W") then
- push = "(" .. push .. ")"
- end
- err = (err == "-") and "–" or Tag.em(err)
- return Tag.span(
- string.format("[-%s, +%s, %s]", pop, push, err),
- {class="apii"}
- )
- end,
-}
-
-local others = prepos("?? "," ??")
-
-local function trata (t)
- t = string.gsub(t, "@(%w+)(%b{})", function (w, f)
- f = trata(string.sub(f, 2, -2))
- if type(Tex[w]) ~= "function" then
- io.stderr:write(w .. "\n")
- return others(f)
- else
- return Tex[w](f, w)
- end
- end)
- return t
-end
-
-
----------------------------------------------------------------------
----------------------------------------------------------------------
-
--- read whole book
-t = io.read"*a"
-
-t = string.gsub(t, "[<>&\128-\255]",
- {["<"] = "<",
- [">"] = ">",
- ["&"] = "&",
- ["\170"] = "ª",
- ["\186"] = "º",
- ["\192"] = "À",
- ["\193"] = "Á",
- ["\194"] = "Â",
- ["\195"] = "Ã",
- ["\199"] = "Ç",
- ["\201"] = "É",
- ["\202"] = "Ê",
- ["\205"] = "Í",
- ["\211"] = "Ó",
- ["\212"] = "Ô",
- ["\218"] = "Ú",
- ["\224"] = "à",
- ["\225"] = "á",
- ["\226"] = "â",
- ["\227"] = "ã",
- ["\231"] = "ç",
- ["\233"] = "é",
- ["\234"] = "ê",
- ["\237"] = "í",
- ["\243"] = "ó",
- ["\244"] = "ô",
- ["\245"] = "õ",
- ["\250"] = "ú",
- ["\252"] = "ü"
- })
-
-t = string.gsub(t, "\n\n+", "\1")
-
-
-
--- complete macros with no arguments
-t = string.gsub(t, "(@%w+)([^{%w])", "%1{}%2")
-
-t = trata(t)
-
--- correct references
-t = string.gsub(t, "\3(.-)\3", ref)
-
--- remove extra space (??)
-t = string.gsub(t, "%s*\4%s*", "")
-
-t = nopara(t)
-
--- HTML 3.2 does not need
(but complains when it is in wrong places :)
-t = string.gsub(t, "", "")
-
-io.write(header, t, footer)
-
diff --git a/manual/manual.of b/manual/manual.of
deleted file mode 100644
index 5eb2fb1f4f..0000000000
--- a/manual/manual.of
+++ /dev/null
@@ -1,9847 +0,0 @@
-@Ci{$Id: manual.of $}
-@C{[(-------------------------------------------------------------------------}
-@manual{
-
-@sect1{@title{Introduction}
-
-Lua is a powerful, efficient, lightweight, embeddable scripting language.
-It supports procedural programming,
-object-oriented programming, functional programming,
-data-driven programming, and data description.
-
-Lua combines simple procedural syntax with powerful data description
-constructs based on associative arrays and extensible semantics.
-Lua is dynamically typed,
-runs by interpreting bytecode with a register-based
-virtual machine,
-and has automatic memory management with
-a generational garbage collection,
-making it ideal for configuration, scripting,
-and rapid prototyping.
-
-Lua is implemented as a library, written in @emphx{clean C},
-the common subset of @N{standard C} and C++.
-The Lua distribution includes a host program called @id{lua},
-which uses the Lua library to offer a complete,
-standalone Lua interpreter,
-for interactive or batch use.
-Lua is intended to be used both as a powerful, lightweight,
-embeddable scripting language for any program that needs one,
-and as a powerful but lightweight and efficient stand-alone language.
-
-As an extension language, Lua has no notion of a @Q{main} program:
-it works @emph{embedded} in a host client,
-called the @emph{embedding program} or simply the @emphx{host}.
-(Frequently, this host is the stand-alone @id{lua} program.)
-The host program can invoke functions to execute a piece of Lua code,
-can write and read Lua variables,
-and can register @N{C functions} to be called by Lua code.
-Through the use of @N{C functions}, Lua can be augmented to cope with
-a wide range of different domains,
-thus creating customized programming languages sharing a syntactical framework.
-
-Lua is free software,
-and is provided as usual with no guarantees,
-as stated in its license.
-The implementation described in this manual is available
-at Lua's official web site, @id{www.lua.org}.
-
-Like any other reference manual,
-this document is dry in places.
-For a discussion of the decisions behind the design of Lua,
-see the technical papers available at Lua's web site.
-For a detailed introduction to programming in Lua,
-see Roberto's book, @emphx{Programming in Lua}.
-
-}
-
-
-@C{-------------------------------------------------------------------------}
-@sect1{basic| @title{Basic Concepts}
-
-@simplesect{
-
-This section describes the basic concepts of the language.
-
-}
-
-@sect2{TypesSec| @title{Values and Types}
-
-Lua is a dynamically typed language.
-This means that
-variables do not have types; only values do.
-There are no type definitions in the language.
-All values carry their own type.
-
-All values in Lua are first-class values.
-This means that all values can be stored in variables,
-passed as arguments to other functions, and returned as results.
-
-There are eight @x{basic types} in Lua:
-@def{nil}, @def{boolean}, @def{number},
-@def{string}, @def{function}, @def{userdata},
-@def{thread}, and @def{table}.
-The type @emph{nil} has one single value, @nil,
-whose main property is to be different from any other value;
-it often represents the absence of a useful value.
-The type @emph{boolean} has two values, @false and @true.
-Both @nil and @false make a condition false;
-they are collectively called @def{false values}.
-Any other value makes a condition true.
-Despite its name,
-@false is frequently used as an alternative to @nil,
-with the key difference that @false behaves
-like a regular value in a table,
-while a @nil in a table represents an absent key.
-
-The type @emph{number} represents both
-integer numbers and real (floating-point) numbers,
-using two @x{subtypes}: @def{integer} and @def{float}.
-Standard Lua uses 64-bit integers and double-precision (64-bit) floats,
-but you can also compile Lua so that it
-uses 32-bit integers and/or single-precision (32-bit) floats.
-The option with 32 bits for both integers and floats
-is particularly attractive
-for small machines and embedded systems.
-(See macro @id{LUA_32BITS} in file @id{luaconf.h}.)
-
-Unless stated otherwise,
-any overflow when manipulating integer values @def{wrap around},
-according to the usual rules of two's complement arithmetic.
-(In other words,
-the actual result is the unique representable integer
-that is equal modulo @M{2@sp{n}} to the mathematical result,
-where @M{n} is the number of bits of the integer type.)
-
-Lua has explicit rules about when each subtype is used,
-but it also converts between them automatically as needed @see{coercion}.
-Therefore,
-the programmer may choose to mostly ignore the difference
-between integers and floats
-or to assume complete control over the representation of each number.
-
-The type @emph{string} represents immutable sequences of bytes.
-@index{eight-bit clean}
-Lua is 8-bit clean:
-strings can contain any 8-bit value,
-including @x{embedded zeros} (@Char{\0}).
-Lua is also encoding-agnostic;
-it makes no assumptions about the contents of a string.
-The length of any string in Lua must fit in a Lua integer,
-and the string plus a small header must fit in @id{size_t}.
-
-Lua can call (and manipulate) functions written in Lua and
-functions written in C @see{functioncall}.
-Both are represented by the type @emph{function}.
-
-The type @emph{userdata} is provided to allow arbitrary @N{C data} to
-be stored in Lua variables.
-A userdata value represents a block of raw memory.
-There are two kinds of userdata:
-@emphx{full userdata},
-which is an object with a block of memory managed by Lua,
-and @emphx{light userdata},
-which is simply a @N{C pointer} value.
-Userdata has no predefined operations in Lua,
-except assignment and identity test.
-By using @emph{metatables},
-the programmer can define operations for full userdata values
-@see{metatable}.
-Userdata values cannot be created or modified in Lua,
-only through the @N{C API}.
-This guarantees the integrity of data owned by
-the host program and @N{C libraries}.
-
-The type @def{thread} represents independent threads of execution
-and it is used to implement coroutines @see{coroutine}.
-Lua threads are not related to operating-system threads.
-Lua supports coroutines on all systems,
-even those that do not support threads natively.
-
-The type @emph{table} implements @x{associative arrays},
-that is, @x{arrays} that can have as indices not only numbers,
-but any Lua value except @nil and @x{NaN}.
-(@emphx{Not a Number} is a special floating-point value
-used by the @x{IEEE 754} standard to represent
-undefined numerical results, such as @T{0/0}.)
-Tables can be @emph{heterogeneous};
-that is, they can contain values of all types (except @nil).
-Any key associated to the value @nil is not considered part of the table.
-Conversely, any key that is not part of a table has
-an associated value @nil.
-
-Tables are the sole data-structuring mechanism in Lua;
-they can be used to represent ordinary arrays, lists,
-symbol tables, sets, records, graphs, trees, etc.
-To represent @x{records}, Lua uses the field name as an index.
-The language supports this representation by
-providing @id{a.name} as syntactic sugar for @T{a["name"]}.
-There are several convenient ways to create tables in Lua
-@see{tableconstructor}.
-
-Like indices,
-the values of table fields can be of any type.
-In particular,
-because functions are first-class values,
-table fields can contain functions.
-Thus tables can also carry @emph{methods} @see{func-def}.
-
-The indexing of tables follows
-the definition of raw equality in the language.
-The expressions @T{a[i]} and @T{a[j]}
-denote the same table element
-if and only if @id{i} and @id{j} are raw equal
-(that is, equal without metamethods).
-In particular, floats with integral values
-are equal to their respective integers
-(e.g., @T{1.0 == 1}).
-To avoid ambiguities,
-any float used as a key that is equal to an integer
-is converted to that integer.
-For instance, if you write @T{a[2.0] = true},
-the actual key inserted into the table will be the integer @T{2}.
-
-
-Tables, functions, threads, and (full) userdata values are @emph{objects}:
-variables do not actually @emph{contain} these values,
-only @emph{references} to them.
-Assignment, parameter passing, and function returns
-always manipulate references to such values;
-these operations do not imply any kind of copy.
-
-The library function @Lid{type} returns a string describing the type
-of a given value @seeF{type}.
-
-}
-
-@sect2{globalenv| @title{Scopes, Variables, and Environments}
-@index{visibility}
-
-A variable name refers to a global or a local variable according
-to the declaration that is in context at that point of the code.
-(For the purposes of this discussion,
-a function's formal parameter is equivalent to a local variable.)
-
-All chunks start with an implicit declaration @T{global *},
-which declares all free names as global variables;
-this preambular declaration becomes void inside the scope of any other
-@Rw{global} declaration,
-as the following example illustrates:
-@verbatim{
-X = 1 -- Ok, global by default
-do
- global Y -- voids the implicit initial declaration
- Y = 1 -- Ok, Y declared as global
- X = 1 -- ERROR, X not declared
-end
-X = 2 -- Ok, global by default again
-}
-So, outside any global declaration,
-Lua works as @x{global-by-default}.
-Inside any global declaration,
-Lua works without a default:
-All variables must be declared.
-
-Lua is a lexically scoped language.
-The scope of a variable declaration begins at the first statement after
-the declaration and lasts until the last non-void statement
-of the innermost block that includes the declaration.
-(@emph{Void statements} are labels and empty statements.)
-
-A declaration shadows any declaration for the same name that
-is in context at the point of the declaration. Inside this
-shadow, any outer declaration for that name is void.
-See the next example:
-@verbatim{
-global print, x
-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)
-}
-
-Notice that, in a declaration like @T{local x = x},
-the new @id{x} being declared is not in scope yet,
-and so the @id{x} on the right-hand side refers to the outside variable.
-
-Because of the @x{lexical scoping} rules,
-local variables can be freely accessed by functions
-defined inside their scope.
-A local variable used by an inner function is called an @def{upvalue}
-(or @emphx{external local variable}, or simply @emphx{external variable})
-inside the inner function.
-
-Notice that each execution of a @Rw{local} statement
-defines new local variables.
-Consider the following example:
-@verbatim{
-a = {}
-local x = 20
-for i = 1, 10 do
- local y = 0
- a[i] = function () y = y + 1; return x + y end
-end
-}
-The loop creates ten closures
-(that is, ten instances of the anonymous function).
-Each of these closures uses a different @id{y} variable,
-while all of them share the same @id{x}.
-
-As we will discuss further in @refsec{variables} and @refsec{assignment},
-any reference to a global variable @id{var}
-is syntactically translated to @T{_ENV.var}.
-Moreover, every chunk is compiled in the scope of
-an external local variable named @id{_ENV} @see{chunks},
-so @id{_ENV} itself is never a free name in a chunk.
-
-Despite the existence of this external @id{_ENV} variable and
-the translation of free names,
-@id{_ENV} is a regular name.
-In particular,
-you can define new variables and parameters with that name.
-(However, you should not define @id{_ENV} as a global variable,
-otherwise @T{_ENV.var} would translate to
-@T{_ENV._ENV.var} and so on, in an infinite loop.)
-Each reference to a global variable name uses the @id{_ENV} that is
-visible at that point in the program.
-
-Any table used as the value of @id{_ENV} is called an @def{environment}.
-
-Lua keeps a distinguished environment called the @def{global environment}.
-This value is kept at a special index in the C registry @see{registry}.
-In Lua, the global variable @Lid{_G} is initialized with this same value.
-(@Lid{_G} is never used internally,
-so changing its value will affect only your own code.)
-
-When Lua loads a chunk,
-the default value for its @id{_ENV} variable
-is the global environment @seeF{load}.
-Therefore, by default,
-global variables in Lua code refer to entries in the global environment
-and, therefore, they act as conventional global variables.
-Moreover, all standard libraries are loaded in the global environment
-and some functions there operate on that environment.
-You can use @Lid{load} (or @Lid{loadfile})
-to load a chunk with a different environment.
-(In C, you have to load the chunk and then change the value
-of its first upvalue; see @See{lua_setupvalue}.)
-
-}
-
-@sect2{error| @title{Error Handling}
-
-Several operations in Lua can @emph{raise} an error.
-An error interrupts the normal flow of the program,
-which can continue by @emph{catching} the error.
-
-Lua code can explicitly raise an error by calling the
-@Lid{error} function.
-(This function never returns.)
-
-To catch errors in Lua,
-you can do a @def{protected call},
-using @Lid{pcall} (or @Lid{xpcall}).
-The function @Lid{pcall} calls a given function in @def{protected mode}.
-Any error while running the function stops its execution,
-and control returns immediately to @id{pcall},
-which returns a status code.
-
-Because Lua is an embedded extension language,
-Lua code starts running by a call
-from @N{C code} in the host program.
-(When you use Lua standalone,
-the @id{lua} application is the host program.)
-Usually, this call is protected;
-so, when an otherwise unprotected error occurs during
-the compilation or execution of a Lua chunk,
-control returns to the host,
-which can take appropriate measures,
-such as printing an error message.
-
-Whenever there is an error,
-an @def{error object}
-is propagated with information about the error.
-Lua itself only generates errors whose error object is a string,
-but programs can generate errors with
-any value as the error object,
-except @nil.
-(Lua will change a @nil as error object to a string message.)
-It is up to the Lua program or its host to handle such error objects.
-For historical reasons,
-an error object is often called an @def{error message},
-even though it does not have to be a string.
-
-
-When you use @Lid{xpcall} (or @Lid{lua_pcall}, in C)
-you can give a @def{message handler}
-to be called in case of errors.
-This function is called with the original error object
-and returns a new error object.
-It is called before the error unwinds the stack,
-so that it can gather more information about the error,
-for instance by inspecting the stack and creating a stack traceback.
-This message handler is still protected by the protected call;
-so, an error inside the message handler
-will call the message handler again.
-If this loop goes on for too long,
-Lua breaks it and returns an appropriate message.
-The message handler is called only for regular runtime errors.
-It is not called for memory-allocation errors
-nor for errors while running finalizers or other message handlers.
-
-Lua also offers a system of @emph{warnings} @seeF{warn}.
-Unlike errors, warnings do not interfere
-in any way with program execution.
-They typically only generate a message to the user,
-although this behavior can be adapted from C @seeC{lua_setwarnf}.
-
-}
-
-@sect2{metatable| @title{Metatables and Metamethods}
-
-Every value in Lua can have a @emph{metatable}.
-This @def{metatable} is an ordinary Lua table
-that defines the behavior of the original value
-under certain events.
-You can change several aspects of the behavior
-of 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 @idx{__add} of the value's metatable.
-If it finds one,
-Lua calls this function to perform the addition.
-
-The key for each event in a metatable is a string
-with the event name prefixed by two underscores;
-the corresponding value is called a @def{metavalue}.
-For most events, the metavalue must be a function,
-which is then called a @def{metamethod}.
-In the previous example, the key is the string @St{__add}
-and the metamethod is the function that performs the addition.
-Unless stated otherwise,
-a metamethod can in fact be any @x{callable value},
-which is either a function or a value with a @idx{__call} metamethod.
-
-You can query the metatable of any value
-using the @Lid{getmetatable} function.
-Lua queries metamethods in metatables using a raw access @seeF{rawget}.
-
-You can replace the metatable of tables
-using the @Lid{setmetatable} function.
-You cannot change the metatable of other types from Lua code,
-except by using the @link{debuglib|debug library}.
-
-Tables and full userdata have individual metatables,
-although multiple tables and userdata can share their metatables.
-Values of all other types share one single metatable per type;
-that is, there is one single metatable for all numbers,
-one for all strings, etc.
-By default, a value has no metatable,
-but the string library sets a metatable for the string type @see{strlib}.
-
-A detailed list of operations controlled by metatables is given next.
-Each event is identified by its corresponding key.
-By convention, all metatable keys used by Lua are composed by
-two underscores followed by lowercase Latin letters.
-
-@description{
-
-@item{@idx{__add}|
-the addition (@T{+}) operation.
-If any operand for an addition is not a number,
-Lua will try to call a metamethod.
-It starts by checking the first operand (even if it is a number);
-if that operand does not define a metamethod for @idx{__add},
-then Lua will check the second operand.
-If Lua can find a metamethod,
-it calls the metamethod with the two operands as arguments,
-and the result of the call
-(adjusted to one value)
-is the result of the operation.
-Otherwise, if no metamethod is found,
-Lua raises an error.
-}
-
-@item{@idx{__sub}|
-the subtraction (@T{-}) operation.
-Behavior similar to the addition operation.
-}
-
-@item{@idx{__mul}|
-the multiplication (@T{*}) operation.
-Behavior similar to the addition operation.
-}
-
-@item{@idx{__div}|
-the division (@T{/}) operation.
-Behavior similar to the addition operation.
-}
-
-@item{@idx{__mod}|
-the modulo (@T{%}) operation.
-Behavior similar to the addition operation.
-}
-
-@item{@idx{__pow}|
-the exponentiation (@T{^}) operation.
-Behavior similar to the addition operation.
-}
-
-@item{@idx{__unm}|
-the negation (unary @T{-}) operation.
-Behavior similar to the addition operation.
-}
-
-@item{@idx{__idiv}|
-the floor division (@T{//}) operation.
-Behavior similar to the addition operation.
-}
-
-@item{@idx{__band}|
-the bitwise AND (@T{&}) operation.
-Behavior similar to the addition operation,
-except that Lua will try a metamethod
-if any operand is neither an integer
-nor a float coercible to an integer @see{coercion}.
-}
-
-@item{@idx{__bor}|
-the bitwise OR (@T{|}) operation.
-Behavior similar to the bitwise AND operation.
-}
-
-@item{@idx{__bxor}|
-the bitwise exclusive OR (binary @T{~}) operation.
-Behavior similar to the bitwise AND operation.
-}
-
-@item{@idx{__bnot}|
-the bitwise NOT (unary @T{~}) operation.
-Behavior similar to the bitwise AND operation.
-}
-
-@item{@idx{__shl}|
-the bitwise left shift (@T{<<}) operation.
-Behavior similar to the bitwise AND operation.
-}
-
-@item{@idx{__shr}|
-the bitwise right shift (@T{>>}) operation.
-Behavior similar to the bitwise AND operation.
-}
-
-@item{@idx{__concat}|
-the concatenation (@T{..}) operation.
-Behavior similar to the addition operation,
-except that Lua will try a metamethod
-if any operand is neither a string nor a number
-(which is always coercible to a string).
-}
-
-@item{@idx{__len}|
-the length (@T{#}) operation.
-If the object is not a string,
-Lua will try its metamethod.
-If there is a metamethod,
-Lua calls it with the object as argument,
-and the result of the call
-(always adjusted to one value)
-is the result of the operation.
-If there is no metamethod but the object is a table,
-then Lua uses the table length operation @see{len-op}.
-Otherwise, Lua raises an error.
-}
-
-@item{@idx{__eq}|
-the equal (@T{==}) operation.
-Behavior similar to the addition operation,
-except that Lua will try a metamethod only when the values
-being compared are either both tables or both full userdata
-and they are not primitively equal.
-The result of the call is always converted to a boolean.
-}
-
-@item{@idx{__lt}|
-the less than (@T{<}) operation.
-Behavior similar to the addition operation,
-except that Lua will try a metamethod only when the values
-being compared are neither both numbers nor both strings.
-Moreover, the result of the call is always converted to a boolean.
-}
-
-@item{@idx{__le}|
-the less equal (@T{<=}) operation.
-Behavior similar to the less than operation.
-}
-
-@item{@idx{__index}|
-The indexing access operation @T{table[key]}.
-This event happens when @id{table} is not a table or
-when @id{key} is not present in @id{table}.
-The metavalue is looked up in the metatable of @id{table}.
-
-The metavalue for this event can be either a function, a table,
-or any value with an @idx{__index} metavalue.
-If it is a function,
-it is called with @id{table} and @id{key} as arguments,
-and the result of the call
-(adjusted to one value)
-is the result of the operation.
-Otherwise,
-the final result is the result of indexing this metavalue with @id{key}.
-This indexing is regular, not raw,
-and therefore can trigger another @idx{__index} metavalue.
-}
-
-@item{@idx{__newindex}|
-The indexing assignment @T{table[key] = value}.
-Like the index event,
-this event happens when @id{table} is not a table or
-when @id{key} is not present in @id{table}.
-The metavalue is looked up in the metatable of @id{table}.
-
-Like with indexing,
-the metavalue for this event can be either a function, a table,
-or any value with an @idx{__newindex} metavalue.
-If it is a function,
-it is called with @id{table}, @id{key}, and @id{value} as arguments.
-Otherwise,
-Lua repeats the indexing assignment over this metavalue
-with the same key and value.
-This assignment is regular, not raw,
-and therefore can trigger another @idx{__newindex} metavalue.
-
-Whenever a @idx{__newindex} metavalue is invoked,
-Lua does not perform the primitive assignment.
-If needed,
-the metamethod itself can call @Lid{rawset}
-to do the assignment.
-}
-
-@item{@idx{__call}|
-The call operation @T{func(args)}.
-This event happens when Lua tries to call a non-function value
-(that is, @id{func} is not a function).
-The metamethod is looked up in @id{func}.
-If present,
-the metamethod is called with @id{func} as its first argument,
-followed by the arguments of the original call (@id{args}).
-All results of the call
-are the results of the operation.
-This is the only metamethod that allows multiple results.
-}
-
-}
-
-In addition to the previous list,
-the interpreter also respects the following keys in metatables:
-@idx{__gc} @see{finalizers},
-@idx{__close} @see{to-be-closed},
-@idx{__mode} @see{weak-table},
-and @idx{__name}.
-(The entry @idx{__name},
-when it contains a string,
-may be used by @Lid{tostring} and in error messages.)
-
-For the unary operators (negation, length, and bitwise NOT),
-the metamethod is computed and called with a dummy second operand,
-equal to the first one.
-This extra operand is only to simplify Lua's internals
-(by making these operators behave like a binary operation)
-and may be removed in future versions.
-For most uses this extra operand is irrelevant.
-
-Because metatables are regular tables,
-they can contain arbitrary fields,
-not only the event names defined above.
-Some functions in the standard library
-(e.g., @Lid{tostring})
-use other fields in metatables for their own purposes.
-
-It is a good practice to add all needed metamethods to a table
-before setting it as a metatable of some object.
-In particular, the @idx{__gc} metamethod works only when this order
-is followed @see{finalizers}.
-It is also a good practice to set the metatable of an object
-right after its creation.
-
-}
-
-@sect2{GC| @title{Garbage Collection}
-
-@simplesect{
-
-Lua performs automatic memory management.
-This means that
-you do not have to worry about allocating memory for new objects
-or freeing it when the objects are no longer needed.
-Lua manages memory automatically by running
-a @def{garbage collector} to collect all @emph{dead} objects.
-All memory used by Lua is subject to automatic management:
-strings, tables, userdata, functions, threads, internal structures, etc.
-
-An object is considered @def{dead}
-as soon as the collector can be sure the object
-will not be accessed again in the normal execution of the program.
-(@Q{Normal execution} here excludes finalizers,
-which resurrect dead objects @see{finalizers},
-and it excludes also some operations using the debug library.)
-Note that the time when the collector can be sure that an object
-is dead may not coincide with the programmer's expectations.
-The only guarantees are that Lua will not collect an object
-that may still be accessed in the normal execution of the program,
-and it will eventually collect an object
-that is inaccessible from Lua.
-(Here,
-@emph{inaccessible from Lua} means that neither a variable nor
-another live object refer to the object.)
-Because Lua has no knowledge about @N{C code},
-it never collects objects accessible through the registry @see{registry},
-which includes the global environment @see{globalenv} and
-the main thread.
-
-
-The garbage collector (GC) in Lua can work in two modes:
-incremental and generational.
-
-The default GC mode with the default parameters
-are adequate for most uses.
-However, programs that waste a large proportion of their time
-allocating and freeing memory can benefit from other settings.
-Keep in mind that the GC behavior is non-portable
-both across platforms and across different Lua releases;
-therefore, optimal settings are also non-portable.
-
-You can change the GC mode and parameters by calling
-@Lid{lua_gc} @N{in C}
-or @Lid{collectgarbage} in Lua.
-You can also use these functions to control the collector directly,
-for instance to stop or restart it.
-
-}
-
-@sect3{incmode| @title{Incremental Garbage Collection}
-
-In incremental mode,
-each GC cycle performs a mark-and-sweep collection in small steps
-interleaved with the program's execution.
-In this mode,
-the collector uses three numbers to control its garbage-collection cycles:
-the @def{garbage-collector pause},
-the @def{garbage-collector step multiplier},
-and the @def{garbage-collector step size}.
-
-The garbage-collector pause
-controls how long the collector waits before starting a new cycle.
-The collector starts a new cycle when the number of bytes
-hits @M{n%} of the total after the previous collection.
-Larger values make the collector less aggressive.
-Values equal to or less than 100 mean the collector will not wait to
-start a new cycle.
-A value of 200 means that the collector waits for
-the total number of bytes to double before starting a new cycle.
-
-The garbage-collector step size controls the
-size of each incremental step,
-specifically how many bytes the interpreter allocates
-before performing a step:
-A value of @M{n} means the interpreter will allocate
-approximately @M{n} bytes between steps.
-
-The garbage-collector step multiplier
-controls how much work each incremental step does.
-A value of @M{n} means the interpreter will execute
-@M{n%} @emphx{units of work} for each word allocated.
-A unit of work corresponds roughly to traversing one slot
-or sweeping one object.
-Larger values make the collector more aggressive.
-Beware that values too small can
-make the collector too slow to ever finish a cycle.
-As a special case, a zero value means unlimited work,
-effectively producing a non-incremental, stop-the-world collector.
-
-}
-
-@sect3{genmode| @title{Generational Garbage Collection}
-
-In generational mode,
-the collector does frequent @emph{minor} collections,
-which traverses only objects recently created.
-If after a minor collection the number of bytes is above a limit,
-the collector shifts to a @emph{major} collection,
-which traverses all objects.
-The collector will then stay doing major collections until
-it detects that the program is generating enough garbage to justify
-going back to minor collections.
-
-The generational mode uses three parameters:
-the @def{minor multiplier}, the @def{minor-major multiplier},
-and the @def{major-minor multiplier}.
-
-The minor multiplier controls the frequency of minor collections.
-For a minor multiplier @M{x},
-a new minor collection will be done when the number of bytes
-grows @M{x%} larger than the number in use just
-after the last major collection.
-For instance, for a multiplier of 20,
-the collector will do a minor collection when the number of bytes
-gets 20% larger than the total after the last major collection.
-
-The minor-major multiplier controls the shift to major collections.
-For a multiplier @M{x},
-the collector will shift to a major collection
-when the number of bytes from old objects grows @M{x%} larger
-than the total after the previous major collection.
-For instance, for a multiplier of 100,
-the collector will do a major collection when the number of old bytes
-gets larger than twice the total after the previous major collection.
-As a special case,
-a value of 0 stops the collector from doing major collections.
-
-The major-minor multiplier controls the shift back to minor collections.
-For a multiplier @M{x},
-the collector will shift back to minor collections
-after a major collection collects at least @M{x%}
-of the bytes allocated during the last cycle.
-In particular, for a multiplier of 0,
-the collector will immediately shift back to minor collections
-after doing one major collection.
-
-}
-
-@sect3{finalizers| @title{Garbage-Collection Metamethods}
-
-You can set garbage-collector metamethods for tables
-and, using the @N{C API},
-for full userdata @see{metatable}.
-These metamethods, called @def{finalizers},
-are called when the garbage collector detects that the
-corresponding table or userdata is dead.
-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.
-
-For an object (table or userdata) to be finalized when collected,
-you must @emph{mark} it for finalization.
-@index{mark (for finalization)}
-You mark an object for finalization when you set its metatable
-and the metatable has a @idx{__gc} metamethod.
-Note that if you set a metatable without a @idx{__gc} field
-and later create that field in the metatable,
-the object will not be marked for finalization.
-
-When a marked object becomes dead,
-it is not collected immediately by the garbage collector.
-Instead, Lua puts it in a list.
-After the collection,
-Lua goes through that list.
-For each object in the list,
-it checks the object's @idx{__gc} metamethod:
-If it is present,
-Lua calls it with the object as its single argument.
-
-At the end of each garbage-collection cycle,
-the finalizers are called in
-the reverse order that the objects were marked for finalization,
-among those collected in that cycle;
-that is, the first finalizer to be called is the one associated
-with the object marked last in the program.
-The execution of each finalizer may occur at any point during
-the execution of the regular code.
-
-Because the object being collected must still be used by the finalizer,
-that object (and other objects accessible only through it)
-must be @emph{resurrected} by Lua.@index{resurrection}
-Usually, this resurrection is transient,
-and the object memory is freed in the next garbage-collection cycle.
-However, if the finalizer stores the object in some global place
-(e.g., a global variable),
-then the resurrection is permanent.
-Moreover, if the finalizer marks a finalizing object for finalization again,
-its finalizer will be called again in the next cycle where the
-object is dead.
-In any case,
-the object memory is freed only in a GC cycle where
-the object is dead and not marked for finalization.
-
-When you close a state @seeF{lua_close},
-Lua calls the finalizers of all objects marked for finalization,
-following the reverse order that they were marked.
-If any finalizer marks objects for collection during that phase,
-these marks have no effect.
-
-Finalizers cannot yield nor run the garbage collector.
-Because they can run in unpredictable times,
-it is good practice to restrict each finalizer
-to the minimum necessary to properly release
-its associated resource.
-
-Any error while running a finalizer generates a warning;
-the error is not propagated.
-
-}
-
-@sect3{weak-table| @title{Weak Tables}
-
-A @def{weak table} is a table whose elements are
-@def{weak references}.
-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.
-
-A weak table can have weak keys, weak values, or both.
-A table with weak values allows the collection of its values,
-but prevents the collection of its keys.
-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
-@idx{__mode} field of its metatable.
-This metavalue, if present, must be one of the following strings:
-@St{k}, for a table with weak keys;
-@St{v}, for a table with weak values;
-or @St{kv}, for a table with both weak keys and values.
-
-A table with weak keys and strong values
-is also called an @def{ephemeron table}.
-In an ephemeron table,
-a value is considered reachable only if its key is reachable.
-In particular,
-if the only reference to a key comes through its value,
-the pair is removed.
-
-Any change in the weakness of a table may take effect only
-at the next collect cycle.
-In particular, if you change the weakness to a stronger mode,
-Lua may still collect some items from that table
-before the change takes effect.
-
-Only objects that have an explicit construction
-are removed from weak tables.
-Values, such as numbers and @x{light @N{C functions}},
-are not subject to garbage collection,
-and therefore are not removed from weak tables
-(unless their associated values are collected).
-Although strings are subject to garbage collection,
-they do not have an explicit construction and
-their equality is by value;
-they behave more like values than like objects.
-Therefore, they are not removed from weak tables.
-
-Resurrected objects
-(that is, objects being finalized
-and objects accessible only through objects being finalized)
-have a special behavior in weak tables.
-They are removed from weak values before running their finalizers,
-but are removed from weak keys only in the next collection
-after running their finalizers, when such objects are actually freed.
-This behavior allows the finalizer to access properties
-associated with the object through weak tables.
-
-If a weak table is among the resurrected objects in a collection cycle,
-it may not be properly cleared until the next cycle.
-
-}
-
-}
-
-@sect2{coroutine| @title{Coroutines}
-
-Lua supports coroutines,
-also called @emphx{collaborative multithreading}.
-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.
-
-You create a coroutine by calling @Lid{coroutine.create}.
-Its sole argument is a function
-that is the main function of the coroutine.
-The @id{create} function only creates a new coroutine and
-returns a handle to it (an object of type @emph{thread});
-it does not start the coroutine.
-
-You execute a coroutine by calling @Lid{coroutine.resume}.
-When you first call @Lid{coroutine.resume},
-passing as its first argument
-a thread returned by @Lid{coroutine.create},
-the coroutine starts its execution by
-calling its main function.
-Extra arguments passed to @Lid{coroutine.resume} are passed
-as arguments to that function.
-After the coroutine starts running,
-it runs until it terminates or @emph{yields}.
-
-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 case of normal termination,
-@Lid{coroutine.resume} returns @true,
-plus any values returned by the coroutine main function.
-In case of errors, @Lid{coroutine.resume} returns @false
-plus the error object.
-In this case, the coroutine does not unwind its stack,
-so that it is possible to inspect it after the error
-with the debug API.
-
-A coroutine yields by calling @Lid{coroutine.yield}.
-When a coroutine yields,
-the corresponding @Lid{coroutine.resume} 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, @Lid{coroutine.resume} also returns @true,
-plus any values passed to @Lid{coroutine.yield}.
-The next time you resume the same coroutine,
-it continues its execution from the point where it yielded,
-with the call to @Lid{coroutine.yield} returning any extra
-arguments passed to @Lid{coroutine.resume}.
-
-Like @Lid{coroutine.create},
-the @Lid{coroutine.wrap} function also creates a coroutine,
-but instead of returning the coroutine itself,
-it returns a function that, when called, resumes the coroutine.
-Any arguments passed to this function
-go as extra arguments to @Lid{coroutine.resume}.
-@Lid{coroutine.wrap} returns all the values returned by @Lid{coroutine.resume},
-except the first one (the boolean error code).
-Unlike @Lid{coroutine.resume},
-the function created by @Lid{coroutine.wrap}
-propagates any error to the caller.
-In this case,
-the function also closes the coroutine @seeF{coroutine.close}.
-
-As an example of how coroutines work,
-consider the following code:
-@verbatim{
-function foo (a)
- print("foo", a)
- return coroutine.yield(2*a)
-end
-
-co = coroutine.create(function (a,b)
- print("co-body", a, b)
- local r = foo(a+1)
- print("co-body", r)
- local r, s = coroutine.yield(a+b, a-b)
- print("co-body", r, s)
- return b, "end"
-end)
-
-print("main", coroutine.resume(co, 1, 10))
-print("main", coroutine.resume(co, "r"))
-print("main", coroutine.resume(co, "x", "y"))
-print("main", coroutine.resume(co, "x", "y"))
-}
-When you run it, it produces the following output:
-@verbatim{
-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
-}
-
-You can also create and manipulate coroutines through the C API:
-see functions @Lid{lua_newthread}, @Lid{lua_resume},
-and @Lid{lua_yield}.
-
-}
-
-}
-
-
-@C{-------------------------------------------------------------------------}
-@sect1{language| @title{The Language}
-
-@simplesect{
-
-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.
-
-Language constructs will be explained using the usual extended BNF notation,
-in which
-@N{@bnfrep{@rep{a}} means 0} or more @rep{a}'s, and
-@N{@bnfopt{@rep{a}} means} an optional @rep{a}.
-Non-terminals are shown like @bnfNter{non-terminal},
-keywords are shown like @rw{kword},
-and other terminal symbols are shown like @bnfter{=}.
-The complete syntax of Lua can be found in @refsec{BNF}
-at the end of this manual.
-
-}
-
-@sect2{lexical| @title{Lexical Conventions}
-
-Lua is a @x{free-form} language.
-It ignores spaces and comments between lexical elements (@x{tokens}),
-except as delimiters between two tokens.
-In source code,
-Lua recognizes as spaces the standard ASCII whitespace
-characters space, form feed, newline,
-carriage return, horizontal tab, and vertical tab.
-
-@def{Names}
-(also called @def{identifiers})
-in Lua can be any string of Latin letters,
-Arabic-Indic digits, and underscores,
-not beginning with a digit and
-not being a reserved word.
-Identifiers are used to name variables, table fields, and labels.
-
-The following @def{keywords} are reserved
-and cannot be used as names:
-@index{reserved words}
-@verbatim{
-and break do else elseif end
-false for function global goto if
-in local nil not or repeat
-return then true until while
-}
-
-Lua is a case-sensitive language:
-@id{and} is a reserved word, but @id{And} and @id{AND}
-are two different, valid names.
-As a convention,
-programs should avoid creating
-names that start with an underscore followed by
-one or more uppercase letters (such as @Lid{_VERSION}).
-
-The following strings denote other @x{tokens}:
-@verbatim{
-+ - * / % ^ #
-& ~ | << >> //
-== ~= <= >= < > =
-( ) { } [ ] ::
-; : , . .. ...
-}
-
-A @def{short literal string}
-can be delimited by matching single or double quotes,
-and can contain the following C-like escape sequences:
-@Char{\a} (bell),
-@Char{\b} (backspace),
-@Char{\f} (form feed),
-@Char{\n} (newline),
-@Char{\r} (carriage return),
-@Char{\t} (horizontal tab),
-@Char{\v} (vertical tab),
-@Char{\\} (backslash),
-@Char{\"} (quotation mark [double quote]),
-and @Char{\'} (apostrophe [single quote]).
-A backslash followed by a line break
-results in a newline in the string.
-The escape sequence @Char{\z} skips the following span
-of whitespace characters,
-including line breaks;
-it is particularly useful to break and indent a long literal string
-into multiple lines without adding the newlines and spaces
-into the string contents.
-A short literal string cannot contain unescaped line breaks
-nor escapes not forming a valid escape sequence.
-
-We can specify any byte in a short literal string,
-including @x{embedded zeros},
-by its numeric value.
-This can be done
-with the escape sequence @T{\x@rep{XX}},
-where @rep{XX} is a sequence of exactly two hexadecimal digits,
-or with the escape sequence @T{\@rep{ddd}},
-where @rep{ddd} is a sequence of up to three decimal digits.
-(Note that if a decimal escape sequence is to be followed by a digit,
-it must be expressed using exactly three digits.)
-
-The @x{UTF-8} encoding of a @x{Unicode} character
-can be inserted in a literal string with
-the escape sequence @T{\u{@rep{XXX}}}
-(with mandatory enclosing braces),
-where @rep{XXX} is a sequence of one or more hexadecimal digits
-representing the character code point.
-This code point can be any value less than @M{2@sp{31}}.
-(Lua uses the original UTF-8 specification here,
-which is not restricted to valid Unicode code points.)
-
-Literal strings can also be defined using a long format
-enclosed by @def{long brackets}.
-We define an @def{opening long bracket of level @rep{n}} as an opening
-square bracket followed by @rep{n} equal signs followed by another
-opening square bracket.
-So, an opening long bracket of @N{level 0} is written as @T{[[}, @C{]]}
-an opening long bracket of @N{level 1} is written as @T{[=[}, @C{]]}
-and so on.
-A @emph{closing long bracket} is defined similarly;
-for instance,
-a closing long bracket of @N{level 4} is written as @C{[[} @T{]====]}.
-A @def{long literal} starts with an opening long bracket of any level and
-ends at the first closing long bracket of the same level.
-It can contain any text except a closing bracket of the same level.
-Literals in this bracketed form can run for several lines,
-do not interpret any escape sequences,
-and ignore long brackets of any other level.
-Any kind of end-of-line sequence
-(carriage return, newline, carriage return followed by newline,
-or newline followed by carriage return)
-is converted to a simple newline.
-When the opening long 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 @Char{a} is coded @N{as 97},
-newline is coded @N{as 10}, and @Char{1} is coded @N{as 49}),
-the five literal strings below denote the same string:
-@verbatim{
-a = 'alo\n123"'
-a = "alo\n123\""
-a = '\97lo\10\04923"'
-a = [[alo
-123"]]
-a = [==[
-alo
-123"]==]
-}
-
-Any byte in a literal string not
-explicitly affected by the previous rules represents itself.
-However, Lua opens files for parsing in text mode,
-and the system's file functions may have problems with
-some control characters.
-So, it is safer to represent
-binary data as a quoted literal with
-explicit escape sequences for the non-text characters.
-
-A @def{numeric constant} (or @def{numeral})
-can be written with an optional fractional part
-and an optional decimal exponent,
-marked by a letter @Char{e} or @Char{E}.
-Lua also accepts @x{hexadecimal constants},
-which start with @T{0x} or @T{0X}.
-Hexadecimal constants also accept an optional fractional part
-plus an optional binary exponent,
-marked by a letter @Char{p} or @Char{P} and written in decimal.
-(For instance, @T{0x1.fp10} denotes 1984,
-which is @M{0x1f / 16} multiplied by @M{2@sp{10}}.)
-
-A numeric constant with a radix point or an exponent
-denotes a float;
-otherwise,
-if its value fits in an integer or it is a hexadecimal constant,
-it denotes an integer;
-otherwise (that is, a decimal integer numeral that overflows),
-it denotes a float.
-Hexadecimal numerals with neither a radix point nor an exponent
-always denote an integer value;
-if the value overflows, it @emph{wraps around}
-to fit into a valid integer.
-
-Examples of valid integer constants are
-@verbatim{
-3 345 0xff 0xBEBADA
-}
-Examples of valid float constants are
-@verbatim{
-3.0 3.1416 314.16e-2 0.31416E1 34e1
-0x0.1E 0xA23p-4 0X1.921FB54442D18P+1
-}
-
-A @def{comment} starts with a double hyphen (@T{--})
-anywhere outside a string.
-If the text immediately after @T{--} is not an opening long bracket,
-the comment is a @def{short comment},
-which runs until the end of the line.
-Otherwise, it is a @def{long comment},
-which runs until the corresponding closing long bracket.
-
-}
-
-@sect2{variables| @title{Variables}
-
-Variables are places that store values.
-There are three kinds of variables in Lua:
-global variables, local variables, and table fields.
-
-A single name can denote a global variable or a local variable
-(or a function's formal parameter,
-which is a particular kind of local variable) @see{globalenv}:
-@Produc{
-@producname{var}@producbody{@bnfNter{Name}}
-}
-@bnfNter{Name} denotes identifiers @see{lexical}.
-
-Because variables are @emph{lexically scoped},
-local variables can be freely accessed by functions
-defined inside their scope @see{globalenv}.
-
-Before the first assignment to a variable, its value is @nil.
-
-Square brackets are used to index a table:
-@Produc{
-@producname{var}@producbody{prefixexp @bnfter{[} exp @bnfter{]}}
-}
-The meaning of accesses to table fields can be changed via metatables
-@see{metatable}.
-
-The syntax @id{var.Name} is just syntactic sugar for
-@T{var["Name"]}:
-@Produc{
-@producname{var}@producbody{prefixexp @bnfter{.} @bnfNter{Name}}
-}
-
-An access to a global variable @id{x}
-is equivalent to @id{_ENV.x}.
-
-}
-
-@sect2{stats| @title{Statements}
-
-@simplesect{
-
-Lua supports an almost conventional set of @x{statements},
-similar to those in other conventional languages.
-This set includes
-blocks, assignments, control structures, function calls,
-and variable declarations.
-
-}
-
-@sect3{@title{Blocks}
-
-A @x{block} is a list of statements,
-which are executed sequentially:
-@Produc{
-@producname{block}@producbody{@bnfrep{stat}}
-}
-Lua has @def{empty statements}
-that allow you to separate statements with semicolons,
-start a block with a semicolon
-or write two semicolons in sequence:
-@Produc{
-@producname{stat}@producbody{@bnfter{;}}
-}
-
-Both function calls and assignments
-can start with an open parenthesis.
-This possibility leads to an ambiguity in Lua's grammar.
-Consider the following fragment:
-@verbatim{
-a = b + c
-(print or io.write)('done')
-}
-The grammar could see this fragment in two ways:
-@verbatim{
-a = b + c(print or io.write)('done')
-
-a = b + c; (print or io.write)('done')
-}
-The current parser always sees such constructions
-in the first way,
-interpreting the open parenthesis
-as the start of the arguments to a call.
-To avoid this ambiguity,
-it is a good practice to always precede with a semicolon
-statements that start with a parenthesis:
-@verbatim{
-;(print or io.write)('done')
-}
-
-A block can be explicitly delimited to produce a single statement:
-@Produc{
-@producname{stat}@producbody{@Rw{do} block @Rw{end}}
-}
-Explicit blocks are useful
-to control the scope of variable declarations.
-Explicit blocks are also sometimes used to
-add a @Rw{return} statement in the middle
-of another block @see{control}.
-
-}
-
-@sect3{chunks| @title{Chunks}
-
-The unit of compilation of Lua is called a @def{chunk}.
-Syntactically,
-a chunk is simply a block:
-@Produc{
-@producname{chunk}@producbody{block}
-}
-
-Lua handles a chunk as the body of an anonymous function
-with a variable number of arguments
-@see{func-def}.
-As such, chunks can define local variables,
-receive arguments, and return values.
-Moreover, such anonymous function is compiled as in the
-scope of an external local variable called @id{_ENV} @see{globalenv}.
-The resulting function always has @id{_ENV} as its only external variable,
-even if it does not use that variable.
-
-A chunk can be stored in a file or in a string inside the host program.
-To execute a chunk,
-Lua first @emph{loads} it,
-precompiling the chunk's code into instructions for a virtual machine,
-and then Lua executes the compiled code
-with an interpreter for the virtual machine.
-
-Chunks can also be precompiled into binary form;
-see the program @idx{luac} and the function @Lid{string.dump} for details.
-Programs in source and compiled forms are interchangeable;
-Lua automatically detects the file type and acts accordingly @seeF{load}.
-Be aware that, unlike source code,
-maliciously crafted binary chunks can crash the interpreter.
-
-}
-
-@sect3{assignment| @title{Assignment}
-
-Lua allows @x{multiple assignments}.
-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:
-@Produc{
-@producname{stat}@producbody{varlist @bnfter{=} explist}
-@producname{varlist}@producbody{var @bnfrep{@bnfter{,} var}}
-@producname{explist}@producbody{exp @bnfrep{@bnfter{,} exp}}
-}
-Expressions are discussed in @See{expressions}.
-
-Before the assignment,
-the list of values is @emph{adjusted} to the length of
-the list of variables @see{multires}.
-
-If a variable is both assigned and read
-inside a multiple assignment,
-Lua ensures that all reads get the value of the variable
-before the assignment.
-Thus the code
-@verbatim{
-i = 3
-i, a[i] = i+1, 20
-}
-sets @T{a[3]} to 20, without affecting @T{a[4]}
-because the @id{i} in @T{a[i]} is evaluated (to 3)
-before it is @N{assigned 4}.
-Similarly, the line
-@verbatim{
-x, y = y, x
-}
-exchanges the values of @id{x} and @id{y},
-and
-@verbatim{
-x, y, z = y, z, x
-}
-cyclically permutes the values of @id{x}, @id{y}, and @id{z}.
-
-Note that this guarantee covers only accesses
-syntactically inside the assignment statement.
-If a function or a metamethod called during the assignment
-changes the value of a variable,
-Lua gives no guarantees about the order of that access.
-
-An assignment to a global name @T{x = val}
-is equivalent to the assignment
-@T{_ENV.x = val} @see{globalenv}.
-
-The meaning of assignments to table fields and
-global variables (which are actually table fields, too)
-can be changed via metatables @see{metatable}.
-
-}
-
-@sect3{control| @title{Control Structures}
-The control structures
-@Rw{if}, @Rw{while}, and @Rw{repeat} have the usual meaning and
-familiar syntax:
-@index{while-do statement}
-@index{repeat-until statement}
-@index{if-then-else statement}
-@Produc{
-@producname{stat}@producbody{@Rw{while} exp @Rw{do} block @Rw{end}}
-@producname{stat}@producbody{@Rw{repeat} block @Rw{until} exp}
-@producname{stat}@producbody{@Rw{if} exp @Rw{then} block
- @bnfrep{@Rw{elseif} exp @Rw{then} block}
- @bnfopt{@Rw{else} block} @Rw{end}}
-}
-Lua also has a @Rw{for} statement, in two flavors @see{for}.
-
-The @x{condition expression} of a
-control structure can return any value.
-Both @false and @nil test false.
-All values different from @nil and @false test true.
-In particular, the number 0 and the empty string also test true.
-
-In the @Rw{repeat}@En@Rw{until} loop,
-the inner block does not end at the @Rw{until} keyword,
-but only after the condition.
-So, the condition can refer to local variables
-declared inside the loop block.
-
-The @Rw{goto} statement transfers the program control to a label.
-For syntactical reasons,
-labels in Lua are considered statements too:
-@index{goto statement}
-@index{label}
-@Produc{
-@producname{stat}@producbody{@Rw{goto} Name}
-@producname{stat}@producbody{label}
-@producname{label}@producbody{@bnfter{::} Name @bnfter{::}}
-}
-
-A label is visible in the entire block where it is defined,
-except inside nested functions.
-A goto can jump to any visible label as long as it does not
-enter into the scope of a variable declaration.
-A label should not be declared
-where a previous label with the same name is visible,
-even if this other label has been declared in an enclosing block.
-
-The @Rw{break} statement terminates the execution of a
-@Rw{while}, @Rw{repeat}, or @Rw{for} loop,
-skipping to the next statement after the loop:
-@index{break statement}
-@Produc{
-@producname{stat}@producbody{@Rw{break}}
-}
-A @Rw{break} ends the innermost enclosing loop.
-
-The @Rw{return} statement is used to return values
-from a function or a chunk
-(which is handled as an anonymous function).
-@index{return statement}
-Functions can return more than one value,
-so the syntax for the @Rw{return} statement is
-@Produc{
-@producname{stat}@producbody{@Rw{return} @bnfopt{explist} @bnfopt{@bnfter{;}}}
-}
-
-The @Rw{return} statement can only be written
-as the last statement of a block.
-If it is necessary to @Rw{return} in the middle of a block,
-then an explicit inner block can be used,
-as in the idiom @T{do return end},
-because now @Rw{return} is the last statement in its (inner) block.
-
-}
-
-@sect3{for| @title{For Statement}
-
-@index{for statement}
-The @Rw{for} statement has two forms:
-one numerical and one generic.
-
-@sect4{@title{The numerical @Rw{for} loop}
-
-The numerical @Rw{for} loop repeats a block of code while a
-control variable goes through an arithmetic progression.
-It has the following syntax:
-@Produc{
-@producname{stat}@producbody{@Rw{for} @bnfNter{Name} @bnfter{=}
- exp @bnfter{,} exp @bnfopt{@bnfter{,} exp} @Rw{do} block @Rw{end}}
-}
-The given identifier (@bnfNter{Name}) defines the control variable,
-which is a new read-only (@id{const}) variable local to the loop body
-(@emph{block}).
-
-The loop starts by evaluating once the three control expressions.
-Their values are called respectively
-the @emph{initial value}, the @emph{limit}, and the @emph{step}.
-If the step is absent, it defaults @N{to 1}.
-
-If both the initial value and the step are integers,
-the loop is done with integers;
-note that the limit may not be an integer.
-Otherwise, the three values are converted to
-floats and the loop is done with floats.
-Beware of floating-point accuracy in this case.
-
-After that initialization,
-the loop body is repeated with the value of the control variable
-going through an arithmetic progression,
-starting at the initial value,
-with a common difference given by the step.
-A negative step makes a decreasing sequence;
-a step equal to zero raises an error.
-The loop continues while the value is less than
-or equal to the limit
-(greater than or equal to for a negative step).
-If the initial value is already greater than the limit
-(or less than, if the step is negative),
-the body is not executed.
-
-For integer loops,
-the control variable never wraps around;
-instead, the loop ends in case of an overflow.
-
-}
-
-@sect4{@title{The generic @Rw{for} loop}
-
-
-The generic @Rw{for} statement works over functions,
-called @def{iterators}.
-On each iteration, the iterator function is called to produce a new value,
-stopping when this new value is @nil.
-The generic @Rw{for} loop has the following syntax:
-@Produc{
-@producname{stat}@producbody{@Rw{for} namelist @Rw{in} explist
- @Rw{do} block @Rw{end}}
-@producname{namelist}@producbody{@bnfNter{Name} @bnfrep{@bnfter{,} @bnfNter{Name}}}
-}
-A @Rw{for} statement like
-@verbatim{
-for @rep{var_1}, @Cdots, @rep{var_n} in @rep{explist} do @rep{body} end
-}
-works as follows.
-
-The names @rep{var_i} declare loop variables local to the loop body.
-The first of these variables is the @emph{control variable},
-which is a read-only (@id{const}) variable.
-
-The loop starts by evaluating @rep{explist}
-to produce four values:
-an @emph{iterator function},
-a @emph{state},
-an initial value for the control variable,
-and a @emph{closing value}.
-
-Then, at each iteration,
-Lua calls the iterator function with two arguments:
-the state and the control variable.
-The results from this call are then assigned to the loop variables,
-following the rules of multiple assignments @see{assignment}.
-If the control variable becomes @nil,
-the loop terminates.
-Otherwise, the body is executed and the loop goes
-to the next iteration.
-
-The closing value behaves like a
-to-be-closed variable @see{to-be-closed},
-which can be used to release resources when the loop ends.
-Otherwise, it does not interfere with the loop.
-
-}
-
-}
-
-@sect3{funcstat| @title{Function Calls as Statements}
-To allow possible side-effects,
-function calls can be executed as statements:
-@Produc{
-@producname{stat}@producbody{functioncall}
-}
-In this case, all returned values are thrown away.
-Function calls are explained in @See{functioncall}.
-
-}
-
-@sect3{localvar| @title{Variable Declarations}
-Local and global variables can be declared anywhere inside a block.
-The declaration can include an initialization:
-@Produc{
-@producname{stat}@producbody{@Rw{local}
- attnamelist @bnfopt{@bnfter{=} explist}}
-@producname{stat}@producbody{@Rw{global}
- attnamelist @bnfopt{@bnfter{=} explist}}
-}
-If there is no initialization,
-local variables are initialized with @nil;
-global variables are left unchanged.
-Otherwise, the initialization gets the same adjustment
-of a multiple assignment @see{assignment}.
-Moreover, for global variables,
-the initialization will raise a runtime error
-if the variable is already defined,
-that is, it has a non-nil value.
-
-The list of names may be prefixed by an attribute
-(a name between angle brackets)
-and each variable name may be postfixed by an attribute:
-@Produc{
-@producname{attnamelist}@producbody{
- @bnfopt{attrib} @bnfNter{Name} @bnfopt{attrib}
- @bnfrep{@bnfter{,} @bnfNter{Name} @bnfopt{attrib}}}
-@producname{attrib}@producbody{@bnfter{<} @bnfNter{Name} @bnfter{>}}
-}
-A prefixed attribute applies to all names in the list;
-a postfixed attribute applies to its particular name.
-There are two possible attributes:
-@id{const}, which declares a @emph{constant} or @emph{read-only} variable,
-@index{constant variable}
-that is, a variable that cannot be used as the left-hand side of an
-assignment,
-and @id{close}, which declares a to-be-closed variable @see{to-be-closed}.
-Only local variables can have the @id{close} attribute.
-A list of variables can contain at most one to-be-closed variable.
-
-Lua offers also a collective declaration for global variables:
-@Produc{
-@producname{stat}@producbody{@Rw{global} @bnfopt{attrib} @bnfter{*}}
-}
-This special form implicitly declares
-as globals all names not explicitly declared previously.
-In particular,
-@T{global *} implicitly declares
-as read-only globals all names not explicitly declared previously;
-see the following example:
-@verbatim{
-global X
-global *
-print(math.pi) -- Ok, 'print' and 'math' are read-only
-X = 1 -- Ok, declared as read-write
-Y = 1 -- Error, Y is read-only
-}
-
-As noted in @See{globalenv},
-all chunks start with an implicit declaration @T{global *},
-but this preambular declaration becomes void inside
-the scope of any other @Rw{global} declaration.
-Therefore, a program that does not use global declarations
-or start with @T{global *}
-has free read-write access to any global;
-a program that starts with @T{global *}
-has free read-only access to any global;
-and a program that starts with any other global declaration
-(e.g., @T{global none}) can only refer to declared variables.
-
-Note that, for global variables,
-the effect of any declaration is only syntactical
-(except for the optional assignment):
-@verbatim{
-global X , _G
-X = 1 -- ERROR
-_ENV.X = 1 -- Ok
-_G.print(X) -- Ok
-foo() -- 'foo' can freely change any global
-}
-
-A chunk is also a block @see{chunks},
-and so variables can be declared in a chunk outside any explicit block.
-
-The visibility rules for variable declarations
-are explained in @See{globalenv}.
-
-}
-
-@sect3{to-be-closed| @title{To-be-closed Variables}
-
-A to-be-closed variable behaves like a constant local variable,
-except that its value is @emph{closed} whenever the variable
-goes out of scope, including normal block termination,
-exiting its block by @Rw{break}/@Rw{goto}/@Rw{return},
-or exiting by an error.
-
-Here, to @emph{close} a value means
-to call its @idx{__close} metamethod.
-When calling the metamethod,
-the value itself is passed as the first argument.
-If there was an error,
-the error object that caused the exit
-is passed as a second argument;
-otherwise, there is no second argument.
-
-The value assigned to a to-be-closed variable
-must have a @idx{__close} metamethod
-or be a false value.
-(@nil and @false are ignored as to-be-closed values.)
-
-If several to-be-closed variables go out of scope at the same event,
-they are closed in the reverse order that they were declared.
-
-If there is any error while running a closing method,
-that error is handled like an error in the regular code
-where the variable was defined.
-After an error,
-the other pending closing methods will still be called.
-
-If a coroutine yields and is never resumed again,
-some variables may never go out of scope,
-and therefore they will never be closed.
-(These variables are the ones created inside the coroutine
-and in scope at the point where the coroutine yielded.)
-Similarly, if a coroutine ends with an error,
-it does not unwind its stack,
-so it does not close any variable.
-In both cases,
-you can either use finalizers
-or call @Lid{coroutine.close} to close the variables.
-However, if the coroutine was created
-through @Lid{coroutine.wrap},
-then its corresponding function will close the coroutine
-in case of errors.
-
-}
-
-}
-
-@sect2{expressions| @title{Expressions}
-
-@simplesect{
-
-The basic expressions in Lua are the following:
-@Produc{
-@producname{exp}@producbody{prefixexp}
-@producname{exp}@producbody{@Rw{nil} @Or @Rw{false} @Or @Rw{true}}
-@producname{exp}@producbody{@bnfNter{Numeral}}
-@producname{exp}@producbody{@bnfNter{LiteralString}}
-@producname{exp}@producbody{functiondef}
-@producname{exp}@producbody{tableconstructor}
-@producname{exp}@producbody{@bnfter{...}}
-@producname{exp}@producbody{exp binop exp}
-@producname{exp}@producbody{unop exp}
-@producname{prefixexp}@producbody{var @Or functioncall @Or
- @bnfter{(} exp @bnfter{)}}
-}
-
-Numerals and literal strings are explained in @See{lexical};
-variables are explained in @See{variables};
-function definitions are explained in @See{func-def};
-function calls are explained in @See{functioncall};
-table constructors are explained in @See{tableconstructor}.
-Vararg expressions,
-denoted by three dots (@Char{...}), can only be used when
-directly inside a variadic function;
-they are explained in @See{func-def}.
-
-
-Binary operators comprise arithmetic operators @see{arith},
-bitwise operators @see{bitwise},
-relational operators @see{rel-ops}, logical operators @see{logic},
-and the concatenation operator @see{concat}.
-Unary operators comprise the unary minus @see{arith},
-the unary bitwise NOT @see{bitwise},
-the unary logical @Rw{not} @see{logic},
-and the unary @def{length operator} @see{len-op}.
-
-}
-
-
-
-@sect3{arith| @title{Arithmetic Operators}
-Lua supports the following @x{arithmetic operators}:
-@description{
-@item{@T{+}|addition}
-@item{@T{-}|subtraction}
-@item{@T{*}|multiplication}
-@item{@T{/}|float division}
-@item{@T{//}|floor division}
-@item{@T{%}|modulo}
-@item{@T{^}|exponentiation}
-@item{@T{-}|unary minus}
-}
-
-With the exception of exponentiation and float division,
-the arithmetic operators work as follows:
-If both operands are integers,
-the operation is performed over integers and the result is an integer.
-Otherwise, if both operands are numbers,
-then they are converted to floats,
-the operation is performed following the machine's rules
-for floating-point arithmetic
-(usually the @x{IEEE 754} standard),
-and the result is a float.
-(The string library coerces strings to numbers in
-arithmetic operations; see @See{coercion} for details.)
-
-Exponentiation and float division (@T{/})
-always convert their operands to floats
-and the result is always a float.
-Exponentiation uses the @ANSI{pow},
-so that it works for non-integer exponents too.
-
-Floor division (@T{//}) is a division
-that rounds the quotient towards minus infinity,
-resulting in the floor of the division of its operands.
-
-Modulo is defined as the remainder of a division
-that rounds the quotient towards minus infinity (floor division).
-
-In case of overflows in integer arithmetic,
-all operations @emphx{wrap around}.
-}
-
-@sect3{bitwise| @title{Bitwise Operators}
-Lua supports the following @x{bitwise operators}:
-@description{
-@item{@T{&}|bitwise AND}
-@item{@T{@VerBar}|bitwise OR}
-@item{@T{~}|bitwise exclusive OR}
-@item{@T{>>}|right shift}
-@item{@T{<<}|left shift}
-@item{@T{~}|unary bitwise NOT}
-}
-
-All bitwise operations convert its operands to integers
-@see{coercion},
-operate on all bits of those integers,
-and result in an integer.
-
-Both right and left shifts fill the vacant bits with zeros.
-Negative displacements shift to the other direction;
-displacements with absolute values equal to or higher than
-the number of bits in an integer
-result in zero (as all bits are shifted out).
-
-}
-
-@sect3{coercion| @title{Coercions and Conversions}
-Lua provides some automatic conversions between some
-types and representations at run time.
-Bitwise operators always convert float operands to integers.
-Exponentiation and float division
-always convert integer operands to floats.
-All other arithmetic operations applied to mixed numbers
-(integers and floats) convert the integer operand to a float.
-The C API also converts both integers to floats and
-floats to integers, as needed.
-Moreover, string concatenation accepts numbers as arguments,
-besides strings.
-
-In a conversion from integer to float,
-if the integer value has an exact representation as a float,
-that is the result.
-Otherwise,
-the conversion gets the nearest higher or
-the nearest lower representable value.
-This kind of conversion never fails.
-
-The conversion from float to integer
-checks whether the float has an exact representation as an integer
-(that is, the float has an integral value and
-it is in the range of integer representation).
-If it does, that representation is the result.
-Otherwise, the conversion fails.
-
-Several places in Lua coerce strings to numbers when necessary.
-In particular,
-the string library sets metamethods that try to coerce
-strings to numbers in all arithmetic operations.
-If the conversion fails,
-the library calls the metamethod of the other operand
-(if present) or it raises an error.
-Note that bitwise operators do not do this coercion.
-
-It is always a good practice not to rely on the
-implicit coercions from strings to numbers,
-as they are not always applied;
-in particular, @T{"1"==1} is false and @T{"1"<1} raises an error
-@see{rel-ops}.
-These coercions exist mainly for compatibility and may be removed
-in future versions of the language.
-
-A string is converted to an integer or a float
-following its syntax and the rules of the Lua lexer.
-The string may have also leading and trailing whitespaces and a sign.
-All conversions from strings to numbers
-accept both a dot and the current locale mark
-as the radix character.
-(The Lua lexer, however, accepts only a dot.)
-If the string is not a valid numeral,
-the conversion fails.
-If necessary, the result of this first step is then converted
-to a specific number subtype following the previous rules
-for conversions between floats and integers.
-
-The conversion from numbers to strings uses a
-non-specified human-readable format.
-To convert numbers to strings in any specific way,
-use the function @Lid{string.format}.
-
-}
-
-@sect3{rel-ops| @title{Relational Operators}
-Lua supports the following @x{relational operators}:
-@description{
-@item{@T{==}|equality}
-@item{@T{~=}|inequality}
-@item{@T{<}|less than}
-@item{@T{>}|greater than}
-@item{@T{<=}|less or equal}
-@item{@T{>=}|greater or equal}
-}
-These operators always result in @false or @true.
-
-Equality (@T{==}) first compares the type of its operands.
-If the types are different, then the result is @false.
-Otherwise, the values of the operands are compared.
-Strings are equal if they have the same byte content.
-Numbers are equal if they denote the same mathematical value.
-
-Tables, userdata, and threads
-are compared by reference:
-two objects are considered equal only if they are the same object.
-Every time you create a new object
-(a table, a userdata, or a thread),
-this new object is different from any previously existing object.
-A function is always equal to itself.
-Functions with any detectable difference
-(different behavior, different definition) are always different.
-Functions created at different times but with no detectable differences
-may be classified as equal or not
-(depending on internal caching details).
-
-You can change the way that Lua compares tables and userdata
-by using the @idx{__eq} metamethod @see{metatable}.
-
-Equality comparisons do not convert strings to numbers
-or vice versa.
-Thus, @T{"0"==0} evaluates to @false,
-and @T{t[0]} and @T{t["0"]} denote different
-entries in a table.
-
-The operator @T{~=} is exactly the negation of equality (@T{==}).
-
-The order operators work as follows.
-If both arguments are numbers,
-then they are compared according to their mathematical values,
-regardless of their subtypes.
-Otherwise, if both arguments are strings,
-then their values are compared according to the current locale.
-Otherwise, Lua tries to call the @idx{__lt} or the @idx{__le}
-metamethod @see{metatable}.
-A comparison @T{a > b} is translated to @T{b < a}
-and @T{a >= b} is translated to @T{b <= a}.
-
-Following the @x{IEEE 754} standard,
-the special value @x{NaN} is considered neither less than,
-nor equal to, nor greater than any value, including itself.
-
-}
-
-@sect3{logic| @title{Logical Operators}
-The @x{logical operators} in Lua are
-@Rw{and}, @Rw{or}, and @Rw{not}.
-Like the control structures @see{control},
-all logical operators consider both @false and @nil as false
-and anything else as true.
-
-The negation operator @Rw{not} always returns @false or @true.
-The conjunction operator @Rw{and} returns its first argument
-if this value is @false or @nil;
-otherwise, @Rw{and} returns its second argument.
-The disjunction operator @Rw{or} returns its first argument
-if this value is different from @nil and @false;
-otherwise, @Rw{or} returns its second argument.
-Both @Rw{and} and @Rw{or} use @x{short-circuit evaluation};
-that is,
-the second operand is evaluated only if necessary.
-Here are some examples:
-@verbatim{
-10 or 20 --> 10
-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
-}
-
-}
-
-@sect3{concat| @title{Concatenation}
-The string @x{concatenation} operator in Lua is
-denoted by two dots (@Char{..}).
-If both operands are strings or numbers,
-then the numbers are converted to strings
-in a non-specified format @see{coercion}.
-Otherwise, the @idx{__concat} metamethod is called @see{metatable}.
-
-}
-
-@sect3{len-op| @title{The Length Operator}
-
-The length operator is denoted by the unary prefix operator @T{#}.
-
-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 operator applied on a table
-returns a @x{border} in that table.
-A @def{border} in a table @id{t} is any non-negative integer
-that satisfies the following condition:
-@verbatim{
-(border == 0 or t[border] ~= nil) and
-(t[border + 1] == nil or border == math.maxinteger)
-}
-In words,
-a border is any positive integer index present in the table
-that is followed by an absent index,
-plus two limit cases:
-zero, when index 1 is absent;
-and the maximum value for an integer, when that index is present.
-Note that keys that are not positive integers
-do not interfere with borders.
-
-A table with exactly one border is called a @def{sequence}.
-For instance, the table @T{{10,20,30,40,50}} is a sequence,
-as it has only one border (5).
-The table @T{{10,20,30,nil,50}} has two borders (3 and 5),
-and therefore it is not a sequence.
-(The @nil at index 4 is called a @emphx{hole}.)
-The table @T{{nil,20,30,nil,nil,60,nil}}
-has three borders (0, 3, and 6),
-so it is not a sequence, too.
-The table @T{{}} is a sequence with border 0.
-
-When @id{t} is a sequence,
-@T{#t} returns its only border,
-which corresponds to the intuitive notion of the length of the sequence.
-When @id{t} is not a sequence,
-@T{#t} can return any of its borders.
-(The exact one depends on details of
-the internal representation of the table,
-which in turn can depend on how the table was populated and
-the memory addresses of its non-numeric keys.)
-
-The computation of the length of a table
-has a guaranteed worst time of @M{O(log n)},
-where @M{n} is the largest integer key in the table.
-
-A program can modify the behavior of the length operator for
-any value but strings through the @idx{__len} metamethod @see{metatable}.
-
-}
-
-@sect3{prec| @title{Precedence}
-@x{Operator precedence} in Lua follows the table below,
-from lower to higher priority:
-@verbatim{
-or
-and
-< > <= >= ~= ==
-|
-~
-&
-<< >>
-..
-+ -
-* / // %
-unary operators (not # - ~)
-^
-}
-As usual,
-you can use parentheses to change the precedences of an expression.
-The concatenation (@Char{..}) and exponentiation (@Char{^})
-operators are right associative.
-All other binary operators are left associative.
-
-}
-
-@sect3{tableconstructor| @title{Table Constructors}
-Table @x{constructors} are expressions that create tables.
-Every time a constructor is evaluated, a new table is created.
-A constructor can be used to create an empty table
-or to create a table and initialize some of its fields.
-The general syntax for constructors is
-@Produc{
-@producname{tableconstructor}@producbody{@bnfter{@Open} @bnfopt{fieldlist} @bnfter{@Close}}
-@producname{fieldlist}@producbody{field @bnfrep{fieldsep field} @bnfopt{fieldsep}}
-@producname{field}@producbody{@bnfter{[} exp @bnfter{]} @bnfter{=} exp @Or
- @bnfNter{Name} @bnfter{=} exp @Or exp}
-@producname{fieldsep}@producbody{@bnfter{,} @Or @bnfter{;}}
-}
-
-Each field of the form @T{[exp1] = exp2} adds to the new table an entry
-with key @id{exp1} and value @id{exp2}.
-A field of the form @T{name = exp} is equivalent to
-@T{["name"] = exp}.
-Fields of the form @id{exp} are equivalent to
-@T{[i] = exp}, where @id{i} are consecutive integers
-starting with 1;
-fields in the other formats do not affect this counting.
-For example,
-@verbatim{
-a = { [f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45 }
-}
-is equivalent to
-@verbatim{
-do
- local t = {}
- t[f(1)] = g
- t[1] = "x" -- 1st exp
- t[2] = "y" -- 2nd exp
- t.x = 1 -- t["x"] = 1
- t[3] = f(x) -- 3rd exp
- t[30] = 23
- t[4] = 45 -- 4th exp
- a = t
-end
-}
-
-The order of the assignments in a constructor is undefined.
-(This order would be relevant only when there are repeated keys.)
-
-If the last field in the list has the form @id{exp}
-and the expression is a multires expression,
-then all values returned by this expression enter the list consecutively
-@see{multires}.
-
-The field list can have an optional trailing separator,
-as a convenience for machine-generated code.
-
-}
-
-@sect3{functioncall| @title{Function Calls}
-A @x{function call} in Lua has the following syntax:
-@Produc{
-@producname{functioncall}@producbody{prefixexp args}
-}
-In a function call,
-first @bnfNter{prefixexp} and @bnfNter{args} are evaluated.
-If the value of @bnfNter{prefixexp} has type @emph{function},
-then this function is called
-with the given arguments.
-Otherwise, if present,
-the @bnfNter{prefixexp} @idx{__call} metamethod is called:
-its first argument is the value of @bnfNter{prefixexp},
-followed by the original call arguments
-@see{metatable}.
-
-The form
-@Produc{
-@producname{functioncall}@producbody{prefixexp @bnfter{:} @bnfNter{Name} args}
-}
-can be used to emulate methods.
-A call @T{v:name(@rep{args})}
-is syntactic sugar for @T{v.name(v, @rep{args})},
-except that @id{v} is evaluated only once.
-
-Arguments have the following syntax:
-@Produc{
-@producname{args}@producbody{@bnfter{(} @bnfopt{explist} @bnfter{)}}
-@producname{args}@producbody{tableconstructor}
-@producname{args}@producbody{@bnfNter{LiteralString}}
-}
-All argument expressions are evaluated before the call.
-A call of the form @T{f{@rep{fields}}} is
-syntactic sugar for @T{f({@rep{fields}})};
-that is, the argument list is a single new table.
-A call of the form @T{f'@rep{string}'}
-(or @T{f"@rep{string}"} or @T{f[[@rep{string}]]})
-is syntactic sugar for @T{f('@rep{string}')};
-that is, the argument list is a single literal string.
-
-A call of the form @T{return @rep{functioncall}} not in the
-scope of a to-be-closed variable is called a @def{tail call}.
-Lua implements @def{proper tail calls}
-(or @def{proper tail recursion}):
-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 @Rw{return} has one single function call as argument,
-and it is outside the scope of any to-be-closed variable.
-This syntax makes the calling function return exactly
-the returns of the called function,
-without any intervening action.
-So, none of the following examples are tail calls:
-@verbatim{
-return (f(x)) -- results adjusted to 1
-return 2 * f(x) -- result multiplied by 2
-return x, f(x) -- additional results
-f(x); return -- results discarded
-return x or f(x) -- results adjusted to 1
-}
-
-}
-
-@sect3{func-def| @title{Function Definitions}
-
-The syntax for a function definition is
-@Produc{
-@producname{functiondef}@producbody{@Rw{function} funcbody}
-@producname{funcbody}@producbody{@bnfter{(} @bnfopt{parlist} @bnfter{)} block @Rw{end}}
-}
-
-The following syntactic sugar simplifies function definitions:
-@Produc{
-@producname{stat}@producbody{@Rw{function} funcname funcbody}
-@producname{stat}@producbody{@Rw{local} @Rw{function} @bnfNter{Name} funcbody}
-@producname{stat}@producbody{@Rw{global} @Rw{function} @bnfNter{Name} funcbody}
-@producname{funcname}@producbody{@bnfNter{Name} @bnfrep{@bnfter{.} @bnfNter{Name}} @bnfopt{@bnfter{:} @bnfNter{Name}}}
-}
-The statement
-@verbatim{
-function f () @rep{body} end
-}
-translates to
-@verbatim{
-f = function () @rep{body} end
-}
-The statement
-@verbatim{
-function t.a.b.c.f () @rep{body} end
-}
-translates to
-@verbatim{
-t.a.b.c.f = function () @rep{body} end
-}
-
-The statement
-@verbatim{
-local function f () @rep{body} end
-}
-translates to
-@verbatim{
-local f; f = function () @rep{body} end
-}
-not to
-@verbatim{
-local f = function () @rep{body} end
-}
-(This only makes a difference when the body of the function
-contains recursive references to @id{f}.)
-Similarly, the statement
-@verbatim{
-global function f () @rep{body} end
-}
-translates to
-@verbatim{
-global f; global f = function () @rep{body} end
-}
-The second @Rw{global} makes the assignment an initialization,
-which will raise an error if that global is already defined.
-
-The @emphx{colon} syntax
-is used to emulate @def{methods},
-adding an implicit extra parameter @idx{self} to the function.
-Thus, the statement
-@verbatim{
-function t.a.b.c:f (@rep{params}) @rep{body} end
-}
-is syntactic sugar for
-@verbatim{
-t.a.b.c.f = function (self, @rep{params}) @rep{body} end
-}
-
-A function definition is an executable expression,
-whose value has type @emph{function}.
-When Lua precompiles a chunk,
-all its function bodies are precompiled too,
-but they are not created yet.
-Then, whenever Lua executes the function definition,
-the function is @emph{instantiated} (or @emph{closed}).
-This function instance, or @emphx{closure},
-is the final value of the expression.
-
-Results are returned using the @Rw{return} statement @see{control}.
-If control reaches the end of a function
-without encountering a @Rw{return} statement,
-then the function returns with no results.
-
-@index{multiple return}
-There is a system-dependent limit on the number of values
-that a function may return.
-This limit is guaranteed to be at least 1000.
-
-@sect4{@title{Parameters}
-
-Parameters act as local variables that are
-initialized with the argument values:
-@Produc{
-@producname{parlist}@producbody{namelist @bnfopt{@bnfter{,} varargparam} @Or
- varargparam}
-@producname{varargparam}@producbody{@bnfter{...} @bnfopt{@bnfNter{Name}}}
-}
-When a Lua function is called,
-it adjusts its list of @x{arguments} to
-the length of its list of parameters @see{multires},
-unless the function is a @def{variadic function},
-which is indicated by three dots (@Char{...})
-at the end of its parameter list.
-A variadic function does not adjust its argument list;
-instead, it collects all extra arguments and supplies them
-to the function through a @def{vararg table}.
-In that table,
-the values at indices 1, 2, etc. are the extra arguments,
-and the value at index @St{n} is the number of extra arguments.
-
-As an example, consider the following definitions:
-@verbatim{
-function f(a, b) end
-function g(a, b, ...) end
-function r() return 1,2,3 end
-}
-Then, we have the following mapping from arguments to parameters and
-to the vararg table:
-@verbatim{
-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, va. table -> {n = 0}
-g(3, 4) a=3, b=4, va. table -> {n = 0}
-g(3, 4, 5, 8) a=3, b=4, va. table -> {5, 8, n = 2}
-g(5, r()) a=5, b=1, va. table -> {2, 3, n = 2}
-}
-
-A vararg table in a variadic function can have an optional name,
-given after the three dots.
-When present,
-that name denotes a read-only local variable that
-refers to the vararg table.
-If the vararg table does not have a name,
-it can only be accessed through a vararg expression.
-
-A vararg expression is also written as three dots,
-and its value is a list of the values in the vararg table,
-from 1 to the integer value at index @St{n}.
-(Therefore, if the code does not modify the vararg table,
-this list corresponds to the extra arguments in the function call.)
-This list behaves like the results from a
-function with multiple results @see{multires}.
-
-As an optimization,
-if the vararg table satisfies some conditions,
-the code does not create an actual table and instead translates
-the indexing expressions and the vararg expressions
-into accesses to the internal vararg data.
-The conditions are as follows:
-If the vararg table has a name,
-that name is not an upvalue in a nested function
-and it is used only as the base table
-in the syntactic constructions @T{t[exp]} or @T{t.id}.
-Note that an anonymous vararg table always satisfy these conditions.
-
-}
-
-}
-
-@sect3{multires| @title{Lists of Expressions, Multiple Results, and Adjustment}
-
-Both function calls and vararg expressions can result in multiple values.
-These expressions are called @def{multires expressions}.
-
-When a multires expression is used as the last element
-of a list of expressions,
-all results from the expression are added to the
-list of values produced by the list of expressions.
-Note that a single expression
-in a place that expects a list of expressions
-is the last expression in that (singleton) list.
-
-These are the places where Lua expects a list of expressions:
-@description{
-
-@item{A @rw{return} statement,
-for instance @T{return e1,e2,e3} @see{control}.}
-
-@item{A table constructor,
-for instance @T{{e1,e2,e3}} @see{tableconstructor}.}
-
-@item{The arguments of a function call,
-for instance @T{foo(e1,e2,e3)} @see{functioncall}.}
-
-@item{A multiple assignment,
-for instance @T{a,b,c = e1,e2,e3} @see{assignment}.}
-
-@item{A local or global declaration,
-which is similar to a multiple assignment.}
-
-@item{The initial values in a generic @rw{for} loop,
-for instance @T{for k in e1,e2,e3 do ... end} @see{for}.}
-
-}
-In the last four cases,
-the list of values from the list of expressions
-must be @emph{adjusted} to a specific length:
-the number of parameters in a call to a non-variadic function
-@see{func-def},
-the number of variables in a multiple assignment or a declaration,
-and exactly four values for a generic @rw{for} loop.
-The @def{adjustment} follows these rules:
-If there are more values than needed,
-the extra values are thrown away;
-if there are fewer values than needed,
-the list is extended with @nil's.
-When the list of expressions ends with a multires expression,
-all results from that expression enter the list of values
-before the adjustment.
-
-When a multires expression is used
-in a list of expressions without being the last element,
-or in a place where the syntax expects a single expression,
-Lua adjusts the result list of that expression to one element.
-As a particular case,
-the syntax expects a single expression inside a parenthesized expression;
-therefore, adding parentheses around a multires expression
-forces it to produce exactly one result.
-
-We seldom need to use a vararg expression in a place
-where the syntax expects a single expression.
-(Usually it is simpler to add a regular parameter before
-the variadic part and use that parameter.)
-When there is such a need,
-we recommend assigning the vararg expression
-to a single variable and using that variable
-in its place.
-
-Here are some examples of uses of multires expressions.
-In all cases, when the construction needs
-@Q{the n-th result} and there is no such result,
-it uses a @nil.
-@verbatim{
-print(x, f()) -- prints x and all results from f().
-print(x, (f())) -- prints x and the first result from f().
-print(f(), x) -- prints the first result from f() and x.
-print(1 + f()) -- prints 1 added to the first result from f().
-local x = ... -- x gets the first vararg argument.
-x,y = ... -- x gets the first vararg argument,
- -- y gets the second vararg argument.
-x,y,z = w, f() -- x gets w, y gets the first result from f(),
- -- z gets the second result from f().
-x,y,z = f() -- x gets the first result from f(),
- -- y gets the second result from f(),
- -- z gets the third result from f().
-x,y,z = f(), g() -- x gets the first result from f(),
- -- y gets the first result from g(),
- -- z gets the second result from g().
-x,y,z = (f()) -- x gets the first result from f(), y and z get nil.
-return f() -- returns all results from f().
-return x, ... -- returns x and all received vararg arguments.
-return x,y,f() -- returns x, y, and all results from f().
-{f()} -- creates a list with all results from f().
-{...} -- creates a list with all vararg arguments.
-{f(), 5} -- creates a list with the first result from f() and 5.
-}
-
-}
-
-}
-
-
-}
-
-
-@C{-------------------------------------------------------------------------}
-@sect1{API| @title{The Application Program Interface}
-
-@simplesect{
-
-@index{C API}
-This section describes the @N{C API} for Lua, that is,
-the set of @N{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 @defid{lua.h}.
-
-Even when we use the term @Q{function},
-any facility in the API may be provided as a macro instead.
-Except where stated otherwise,
-all such macros use each of their arguments exactly once
-(except for the first argument, which is always a Lua state),
-and so do not generate any hidden side-effects.
-
-As in most @N{C libraries},
-the Lua API functions do not check their arguments
-for validity or consistency.
-However, you can change this behavior by compiling Lua
-with the macro @defid{LUA_USE_APICHECK} defined.
-
-The Lua library is fully reentrant:
-it has no global variables.
-It keeps all information it needs in a dynamic structure,
-called the @def{Lua state}.
-
-Each Lua state has one or more threads,
-which correspond to independent, cooperative lines of execution.
-The type @Lid{lua_State} (despite its name) refers to a thread.
-(Indirectly, through the thread, it also refers to the
-Lua state associated to the thread.)
-
-A pointer to a thread must be passed as the first argument to
-every function in the library, except to @Lid{lua_newstate},
-which creates a Lua state from scratch and returns a pointer
-to the @emph{main thread} in the new state.
-
-}
-
-
-@sect2{@title{The Stack}
-
-@simplesect{
-
-Lua uses a @emph{virtual stack} to pass values to and from C.
-Each element in this stack represents a Lua value
-(@nil, number, string, etc.).
-Functions in the API can access this stack through the
-Lua state parameter that they receive.
-
-Whenever Lua calls C, the called function gets a new stack,
-which is independent of previous stacks and of stacks of
-@N{C functions} that are still active.
-This stack initially contains any arguments to the @N{C function}
-and it is where the @N{C function} can store temporary
-Lua values and must push its results
-to be returned to the caller @seeC{lua_CFunction}.
-
-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 @emph{index}:@index{index (API stack)}
-A positive index represents an absolute stack position,
-starting @N{at 1} as the bottom of the stack;
-a negative index represents an offset relative to the top of the stack.
-More specifically, if the stack has @rep{n} elements,
-then @N{index 1} represents the first element
-(that is, the element that was pushed onto the stack first)
-and
-@N{index @rep{n}} represents the last element;
-@N{index @num{-1}} also represents the last element
-(that is, the element at @N{the top})
-and index @M{-n} represents the first element.
-
-}
-
-@sect3{stacksize| @title{Stack Size}
-
-When you interact with the Lua API,
-you are responsible for ensuring consistency.
-In particular,
-@emph{you are responsible for controlling stack overflow}.
-When you call any API function,
-you must ensure the stack has enough room to accommodate the results.
-
-There is one exception to the above rule:
-When you call a Lua function
-without a fixed number of results @seeF{lua_call},
-Lua ensures that the stack has enough space for all results.
-However, it does not ensure any extra space.
-So, before pushing anything on the stack after such a call
-you should use @Lid{lua_checkstack}.
-
-Whenever Lua calls C,
-it ensures that the stack has space for
-at least @defid{LUA_MINSTACK} extra elements;
-that is, you can safely push up to @id{LUA_MINSTACK} values into it.
-@id{LUA_MINSTACK} 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.
-Whenever necessary,
-you can use the function @Lid{lua_checkstack}
-to ensure that the stack has enough space for pushing new elements.
-
-}
-
-@sect3{@title{Valid and Acceptable Indices}
-
-Any function in the API that receives stack indices
-works only with @emphx{valid indices} or @emphx{acceptable indices}.
-
-A @def{valid index} is an index that refers to a
-position that stores a modifiable Lua value.
-It comprises stack indices @N{between 1} and the stack top
-(@T{1 @leq abs(index) @leq top})
-@index{stack index}
-plus @def{pseudo-indices},
-which represent some positions that are accessible to @N{C code}
-but that are not in the stack.
-Pseudo-indices are used to access the registry @see{registry}
-and the upvalues of a @N{C function} @see{c-closure}.
-
-Functions that do not need a specific mutable position,
-but only a value (e.g., query functions),
-can be called with acceptable indices.
-An @def{acceptable index} can be any valid index,
-but it also can be any positive index after the stack top
-within the space allocated for the stack,
-that is, indices up to the stack size.
-(Note that 0 is never an acceptable index.)
-Indices to upvalues @see{c-closure} greater than the real number
-of upvalues in the current @N{C function} are also acceptable (but invalid).
-Except when noted otherwise,
-functions in the API work with acceptable indices.
-
-Acceptable indices serve to avoid extra tests
-against the stack top when querying the stack.
-For instance, a @N{C function} can query its third argument
-without the need to check whether there is a third argument,
-that is, without the need to check whether 3 is a valid index.
-
-For functions that can be called with acceptable indices,
-any non-valid index is treated as if it
-contains a value of a virtual type @defid{LUA_TNONE},
-which behaves like a nil value.
-
-}
-
-@sect3{constchar|@title{Pointers to Strings}
-
-Several functions in the API accept pointers (@T{const char*})
-to C strings.
-Some of there parameters have an associated length (@T{size_t}).
-Unless stated otherwise,
-when there is an associated length,
-the string can contain embedded zeros;
-moreover, the pointer can be @id{NULL} if the length is zero.
-When there is no associated length,
-the pointer must point to a zero-terminated string.
-In any case, the string contents should remain unchanged
-until the function returns.
-
-Several functions in the API also return pointers (@T{const char*})
-to Lua strings in the stack.
-(See @Lid{lua_pushfstring}, @Lid{lua_pushlstring},
-@Lid{lua_pushstring}, and @Lid{lua_tolstring}.
-See also @Lid{luaL_checklstring}, @Lid{luaL_checkstring},
-and @Lid{luaL_tolstring} in the auxiliary library.)
-
-In general,
-Lua's garbage collection can free or move memory
-and then invalidate pointers to strings handled by a Lua state.
-To allow a safe use of these pointers,
-the API guarantees that any pointer to a string in a stack index
-is valid while the string value at that index is not removed from the stack.
-(It can be moved to another index, though.)
-When the index is a pseudo-index (referring to an upvalue),
-the pointer is valid while the corresponding call is active and
-the corresponding upvalue is not modified.
-
-Some functions in the debug interface
-also return pointers to strings,
-namely @Lid{lua_getlocal}, @Lid{lua_getupvalue},
-@Lid{lua_setlocal}, and @Lid{lua_setupvalue}.
-For these functions, the pointer is guaranteed to
-be valid while the caller function is active and
-the given closure (if one was given) is in the stack.
-
-Except for these guarantees,
-the garbage collector is free to invalidate
-any pointer to internal strings.
-
-}
-
-}
-
-@sect2{c-closure| @title{C Closures}
-
-When a @N{C function} is created,
-it is possible to associate some values with it,
-thus creating a @def{@N{C closure}}
-@seeC{lua_pushcclosure};
-these values are called @def{upvalues} and are
-accessible to the function whenever it is called.
-
-Whenever a @N{C function} is called,
-its upvalues are located at specific pseudo-indices.
-These pseudo-indices are produced by the macro
-@Lid{lua_upvalueindex}.
-The first upvalue associated with a function is at index
-@T{lua_upvalueindex(1)}, and so on.
-Any access to @T{lua_upvalueindex(@rep{n})},
-where @rep{n} is greater than the number of upvalues of the
-current function
-(but not greater than 256,
-which is one plus the maximum number of upvalues in a closure),
-produces an acceptable but invalid index.
-
-A @N{C closure} can also change the values
-of its corresponding upvalues.
-
-}
-
-@sect2{registry| @title{Registry}
-
-Lua provides a @def{registry},
-a predefined table that can be used by any @N{C code} to
-store whatever Lua values it needs to store.
-The registry table is always accessible at pseudo-index
-@defid{LUA_REGISTRYINDEX}.
-Any @N{C library} can store data into this table,
-but it must take care to choose keys
-that are different from those used
-by other libraries, to avoid collisions.
-Typically, you should use as key a string containing your library name,
-or a light userdata with the address of a @N{C object} in your code,
-or any Lua object created by your code.
-As with variable names,
-string keys starting with an underscore followed by
-uppercase letters are reserved for Lua.
-
-The integer keys in the registry are used
-by the reference mechanism @seeC{luaL_ref},
-with some predefined values.
-Therefore, integer keys in the registry
-must not be used for other purposes.
-
-When you create a new Lua state,
-its registry comes with some predefined values.
-These predefined values are indexed with integer keys
-defined as constants in @id{lua.h}.
-The following constants are defined:
-@description{
-@item{@defid{LUA_RIDX_MAINTHREAD}| At this index the registry has
-the main thread of the state.
-(The main thread is the one created together with the state.)
-}
-
-@item{@defid{LUA_RIDX_GLOBALS}| At this index the registry has
-the @x{global environment}.
-}
-}
-
-}
-
-@sect2{C-error|@title{Error Handling in C}
-
-@simplesect{
-
-Internally, Lua uses the C @id{longjmp} facility to handle errors.
-(Lua will use exceptions if you compile it as C++;
-search for @id{LUAI_THROW} in the source code for details.)
-When Lua faces any error,
-such as a @x{memory allocation error} or a type error,
-it @emph{raises} an error;
-that is, it does a long jump.
-A @emphx{protected environment} uses @id{setjmp}
-to set a recovery point;
-any error jumps to the most recent active recovery point.
-
-Inside a @N{C function} you can raise an error explicitly
-by calling @Lid{lua_error}.
-
-Most functions in the API can raise an error,
-for instance due to a @x{memory allocation error}.
-The documentation for each function indicates whether
-it can raise errors.
-
-If an error happens outside any protected environment,
-Lua calls a @def{panic function} (see @Lid{lua_atpanic})
-and then calls @T{abort},
-thus exiting the host application.
-Your panic function can avoid this exit by
-never returning
-(e.g., doing a long jump to your own recovery point outside Lua).
-
-The panic function,
-as its name implies,
-is a mechanism of last resort.
-Programs should avoid it.
-As a general rule,
-when a @N{C function} is called by Lua with a Lua state,
-it can do whatever it wants on that Lua state,
-as it should be already protected.
-However,
-when C code operates on other Lua states
-(e.g., a Lua-state argument to the function,
-a Lua state stored in the registry, or
-the result of @Lid{lua_newthread}),
-it should use them only in API calls that cannot raise errors.
-
-The panic function runs as if it were a @x{message handler} @see{error};
-in particular, the error object is on the top of the stack.
-However, there is no guarantee about stack space.
-To push anything on the stack,
-the panic function must first check the available space @see{stacksize}.
-
-}
-
-
-@sect3{statuscodes|@title{Status Codes}
-
-Several functions that report errors in the API use the following
-status codes to indicate different kinds of errors or other conditions:
-@description{
-
-@item{@defid{LUA_OK} (0)| no errors.}
-
-@item{@defid{LUA_ERRRUN}| a runtime error.}
-
-@item{@defid{LUA_ERRMEM}|
-@x{memory allocation error}.
-For such errors, Lua does not call the @x{message handler}.
-}
-
-@item{@defid{LUA_ERRERR}|
-stack overflow while running the @x{message handler}
-due to another stack overflow.
-More often than not,
-this error is the result of some other error while running
-a message handler.
-An error in a message handler will call the handler again,
-which will generate the error again, and so on,
-until this loop exhausts the stack and cause this error.
-}
-
-@item{@defid{LUA_ERRSYNTAX}| syntax error during precompilation
-or format error in a binary chunk.}
-
-@item{@defid{LUA_YIELD}| the thread (coroutine) yields.}
-
-@item{@defid{LUA_ERRFILE}| a file-related error;
-e.g., it cannot open or read the file.}
-
-}
-These constants are defined in the header file @id{lua.h}.
-
-}
-
-}
-
-@sect2{continuations|@title{Handling Yields in C}
-
-Internally, Lua uses the C @id{longjmp} facility to yield a coroutine.
-Therefore, if a @N{C function} @id{foo} calls an API function
-and this API function yields
-(directly or indirectly by calling another function that yields),
-Lua cannot return to @id{foo} any more,
-because the @id{longjmp} removes its frame from the @N{C stack}.
-
-To avoid this kind of problem,
-Lua raises an error whenever it tries to yield across an API call,
-except for three functions:
-@Lid{lua_yieldk}, @Lid{lua_callk}, and @Lid{lua_pcallk}.
-All those functions receive a @def{continuation function}
-(as a parameter named @id{k}) to continue execution after a yield.
-
-We need to set some terminology to explain continuations.
-We have a @N{C function} called from Lua which we will call
-the @emph{original function}.
-This original function then calls one of those three functions in the C API,
-which we will call the @emph{callee function},
-that then yields the current thread.
-This can happen when the callee function is @Lid{lua_yieldk},
-or when the callee function is either @Lid{lua_callk} or @Lid{lua_pcallk}
-and the function called by them yields.
-
-Suppose the running thread yields while executing the callee function.
-After the thread resumes,
-it eventually will finish running the callee function.
-However,
-the callee function cannot return to the original function,
-because its frame in the @N{C stack} was destroyed by the yield.
-Instead, Lua calls a @def{continuation function},
-which was given as an argument to the callee function.
-As the name implies,
-the continuation function should continue the task
-of the original function.
-
-As an illustration, consider the following function:
-@verbatim{
-int original_function (lua_State *L) {
- ... /* code 1 */
- status = lua_pcall(L, n, m, h); /* calls Lua */
- ... /* code 2 */
-}
-}
-Now we want to allow
-the Lua code being run by @Lid{lua_pcall} to yield.
-First, we can rewrite our function like here:
-@verbatim{
-int k (lua_State *L, int status, lua_KContext ctx) {
- ... /* code 2 */
-}
-
-int original_function (lua_State *L) {
- ... /* code 1 */
- return k(L, lua_pcall(L, n, m, h), ctx);
-}
-}
-In the above code,
-the new function @id{k} is a
-@emph{continuation function} (with type @Lid{lua_KFunction}),
-which should do all the work that the original function
-was doing after calling @Lid{lua_pcall}.
-Now, we must inform Lua that it must call @id{k} if the Lua code
-being executed by @Lid{lua_pcall} gets interrupted in some way
-(errors or yielding),
-so we rewrite the code as here,
-replacing @Lid{lua_pcall} by @Lid{lua_pcallk}:
-@verbatim{
-int original_function (lua_State *L) {
- ... /* code 1 */
- return k(L, lua_pcallk(L, n, m, h, ctx2, k), ctx1);
-}
-}
-Note the external, explicit call to the continuation:
-Lua will call the continuation only if needed, that is,
-in case of errors or resuming after a yield.
-If the called function returns normally without ever yielding,
-@Lid{lua_pcallk} (and @Lid{lua_callk}) will also return normally.
-(Of course, instead of calling the continuation in that case,
-you can do the equivalent work directly inside the original function.)
-
-Besides the Lua state,
-the continuation function has two other parameters:
-the final status of the call and the context value (@id{ctx}) that
-was passed originally to @Lid{lua_pcallk}.
-Lua does not use this context value;
-it only passes this value from the original function to the
-continuation function.
-For @Lid{lua_pcallk},
-the status is the same value that would be returned by @Lid{lua_pcallk},
-except that it is @Lid{LUA_YIELD} when being executed after a yield
-(instead of @Lid{LUA_OK}).
-For @Lid{lua_yieldk} and @Lid{lua_callk},
-the status is always @Lid{LUA_YIELD} when Lua calls the continuation.
-(For these two functions,
-Lua will not call the continuation in case of errors,
-because they do not handle errors.)
-Similarly, when using @Lid{lua_callk},
-you should call the continuation function
-with @Lid{LUA_OK} as the status.
-(For @Lid{lua_yieldk}, there is not much point in calling
-directly the continuation function,
-because @Lid{lua_yieldk} usually does not return.)
-
-Lua treats the continuation function as if it were the original function.
-The continuation function receives the same Lua stack
-from the original function,
-in the same state it would be if the callee function had returned.
-(For instance,
-after a @Lid{lua_callk} the function and its arguments are
-removed from the stack and replaced by the results from the call.)
-It also has the same upvalues.
-Whatever it returns is handled by Lua as if it were the return
-of the original function.
-
-}
-
-@sect2{@title{Functions and Types}
-
-Here we list all functions and types from the @N{C API} in
-alphabetical order.
-Each function has an indicator like this:
-@apii{o,p,x}
-
-The first field, @T{o},
-is how many elements the function pops from the stack.
-The second field, @T{p},
-is how many elements the function pushes onto the stack.
-(Any function always pushes its results after popping its arguments.)
-A field in the form @T{x|y} means the function can push (or pop)
-@T{x} or @T{y} elements,
-depending on the situation;
-an interrogation mark @Char{?} means that
-we cannot know how many elements the function pops/pushes
-by looking only at its arguments.
-(For instance, they may depend on what is in the stack.)
-The third field, @T{x},
-tells whether the function may raise errors:
-@Char{-} means the function never raises any error;
-@Char{m} means the function may raise only out-of-memory errors;
-@Char{v} means the function may raise the errors explained in the text;
-@Char{e} means the function can run arbitrary Lua code,
-either directly or through metamethods,
-and therefore may raise any errors.
-
-
-@APIEntry{int lua_absindex (lua_State *L, int idx);|
-@apii{0,0,-}
-
-Converts the @x{acceptable index} @id{idx}
-into an equivalent @x{absolute index}
-(that is, one that does not depend on the stack size).
-
-}
-
-
-@APIEntry{
-typedef void * (*lua_Alloc) (void *ud,
- void *ptr,
- size_t osize,
- size_t nsize);|
-
-The type of the @x{memory-allocator function} used by Lua states.
-The allocator function must provide a
-functionality similar to @id{realloc},
-but not exactly the same.
-Its arguments are
-@id{ud}, an opaque pointer passed to @Lid{lua_newstate};
-@id{ptr}, a pointer to the block being allocated/reallocated/freed;
-@id{osize}, the original size of the block or some code about what
-is being allocated;
-and @id{nsize}, the new size of the block.
-
-When @id{ptr} is not @id{NULL},
-@id{osize} is the size of the block pointed by @id{ptr},
-that is, the size given when it was allocated or reallocated.
-
-When @id{ptr} is @id{NULL},
-@id{osize} encodes the kind of object that Lua is allocating.
-@id{osize} is any of
-@Lid{LUA_TSTRING}, @Lid{LUA_TTABLE}, @Lid{LUA_TFUNCTION},
-@Lid{LUA_TUSERDATA}, or @Lid{LUA_TTHREAD} when (and only when)
-Lua is creating a new object of that type.
-When @id{osize} is some other value,
-Lua is allocating memory for something else.
-
-Lua assumes the following behavior from the allocator function:
-
-When @id{nsize} is zero,
-the allocator must behave like @id{free}
-and then return @id{NULL}.
-
-When @id{nsize} is not zero,
-the allocator must behave like @id{realloc}.
-In particular, the allocator returns @id{NULL}
-if and only if it cannot fulfill the request.
-
-Here is a simple implementation for the @x{allocator function},
-corresponding to the function @Lid{luaL_alloc} from the
-auxiliary library.
-@verbatim{
-void *luaL_alloc (void *ud, void *ptr, size_t osize,
- size_t nsize) {
- (void)ud; (void)osize; /* not used */
- if (nsize == 0) {
- free(ptr);
- return NULL;
- }
- else
- return realloc(ptr, nsize);
-}
-}
-Note that @N{ISO C} ensures
-that @T{free(NULL)} has no effect and that
-@T{realloc(NULL,size)} is equivalent to @T{malloc(size)}.
-
-}
-
-@APIEntry{void lua_arith (lua_State *L, int op);|
-@apii{2|1,1,e}
-
-Performs an arithmetic or bitwise operation over the two values
-(or one, in the case of negations)
-at the top of the stack,
-with the value on the top being the second operand,
-pops these values, and pushes the result of the operation.
-The function follows the semantics of the corresponding Lua operator
-(that is, it may call metamethods).
-
-The value of @id{op} must be one of the following constants:
-@description{
-
-@item{@defid{LUA_OPADD}| performs addition (@T{+})}
-@item{@defid{LUA_OPSUB}| performs subtraction (@T{-})}
-@item{@defid{LUA_OPMUL}| performs multiplication (@T{*})}
-@item{@defid{LUA_OPDIV}| performs float division (@T{/})}
-@item{@defid{LUA_OPIDIV}| performs floor division (@T{//})}
-@item{@defid{LUA_OPMOD}| performs modulo (@T{%})}
-@item{@defid{LUA_OPPOW}| performs exponentiation (@T{^})}
-@item{@defid{LUA_OPUNM}| performs mathematical negation (unary @T{-})}
-@item{@defid{LUA_OPBNOT}| performs bitwise NOT (@T{~})}
-@item{@defid{LUA_OPBAND}| performs bitwise AND (@T{&})}
-@item{@defid{LUA_OPBOR}| performs bitwise OR (@T{|})}
-@item{@defid{LUA_OPBXOR}| performs bitwise exclusive OR (@T{~})}
-@item{@defid{LUA_OPSHL}| performs left shift (@T{<<})}
-@item{@defid{LUA_OPSHR}| performs right shift (@T{>>})}
-
-}
-
-}
-
-@APIEntry{lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf);|
-@apii{0,0,-}
-
-Sets a new panic function and returns the old one @see{C-error}.
-
-}
-
-@APIEntry{void lua_call (lua_State *L, int nargs, int nresults);|
-@apii{nargs+1,nresults,e}
-
-Calls a function.
-Like regular Lua calls,
-@id{lua_call} respects the @idx{__call} metamethod.
-So, here the word @Q{function}
-means any callable value.
-
-To do a call you must use the following protocol:
-first, the function to be called is pushed onto the stack;
-then, the arguments to the call are pushed
-in direct order;
-that is, the first argument is pushed first.
-Finally you call @Lid{lua_call};
-@id{nargs} is the number of arguments that you pushed onto the stack.
-When the function returns,
-all arguments and the function value are popped
-and the call results are pushed onto the stack.
-The number of results is adjusted to @id{nresults},
-unless @id{nresults} is @defid{LUA_MULTRET},
-which makes all results from the function to be pushed.
-In the first case, an explicit number of results,
-the caller must ensure that the stack has space for the
-returned values.
-In the second case, all results,
-Lua takes care that the returned values fit into the stack space,
-but it does not ensure any extra space in the stack.
-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 of the stack.
-
-The maximum value for @id{nresults} is 250.
-
-Any error while calling and running the function is propagated upwards
-(with a @id{longjmp}).
-
-The following example shows how the host program can do the
-equivalent to this Lua code:
-@verbatim{
-a = f("how", t.x, 14)
-}
-Here it is @N{in C}:
-@verbatim{
-lua_getglobal(L, "f"); /* function to be called */
-lua_pushliteral(L, "how"); /* 1st argument */
-lua_getglobal(L, "t"); /* table to be indexed */
-lua_getfield(L, -1, "x"); /* push result of t.x (2nd arg) */
-lua_remove(L, -2); /* remove 't' from the stack */
-lua_pushinteger(L, 14); /* 3rd argument */
-lua_call(L, 3, 1); /* call 'f' with 3 arguments and 1 result */
-lua_setglobal(L, "a"); /* set global 'a' */
-}
-Note that the code above is @emph{balanced}:
-at its end, the stack is back to its original configuration.
-This is considered good programming practice.
-
-}
-
-@APIEntry{
-void lua_callk (lua_State *L,
- int nargs,
- int nresults,
- lua_KContext ctx,
- lua_KFunction k);|
-@apii{nargs + 1,nresults,e}
-
-This function behaves exactly like @Lid{lua_call},
-but allows the called function to yield @see{continuations}.
-
-}
-
-@APIEntry{typedef int (*lua_CFunction) (lua_State *L);|
-
-Type for @N{C functions}.
-
-In order to communicate properly with Lua,
-a @N{C function} must use the following protocol,
-which defines the way parameters and results are passed:
-a @N{C function} receives its arguments from Lua in its stack
-in direct order (the first argument is pushed first).
-So, when the function starts,
-@T{lua_gettop(L)} returns the number of arguments received by the function.
-The first argument (if any) is at index 1
-and its last argument is at index @T{lua_gettop(L)}.
-To return values to Lua, a @N{C function} just pushes them onto the stack,
-in direct order (the first result is pushed first),
-and returns in C the number of results.
-Any other value in the stack below the results will be properly
-discarded by Lua.
-Like a Lua function, a @N{C function} called by Lua can also return
-many results.
-
-As an example, the following function receives a variable number
-of numeric arguments and returns their average and their sum:
-@verbatim{
-static int foo (lua_State *L) {
- int n = lua_gettop(L); /* number of arguments */
- lua_Number sum = 0.0;
- int i;
- for (i = 1; i <= n; i++) {
- if (!lua_isnumber(L, i)) {
- lua_pushliteral(L, "incorrect argument");
- 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 */
-}
-}
-
-
-
-}
-
-
-@APIEntry{int lua_checkstack (lua_State *L, int n);|
-@apii{0,0,-}
-
-Ensures that the stack has space for at least @id{n} extra elements,
-that is, that you can safely push up to @id{n} values into it.
-It returns false if it cannot fulfill the request,
-either because it would cause the stack
-to be greater than a fixed maximum size
-(typically at least several thousand elements) or
-because it cannot allocate memory for the extra space.
-This function never shrinks the stack;
-if the stack already has space for the extra elements,
-it is left unchanged.
-
-}
-
-@APIEntry{void lua_close (lua_State *L);|
-@apii{0,0,-}
-
-Close all active to-be-closed variables in the main thread,
-release all objects in the given Lua state
-(calling the corresponding garbage-collection metamethods, if any),
-and frees all dynamic memory used by this 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 that create multiple states,
-such as daemons or web servers,
-will probably need to close states as soon as they are not needed.
-
-}
-
-@APIEntry{void lua_closeslot (lua_State *L, int index);|
-@apii{0,0,e}
-
-Close the to-be-closed slot at the given index and set its value to @nil.
-The index must be the last index previously marked to be closed
-@see{lua_toclose} that is still active (that is, not closed yet).
-
-A @idx{__close} metamethod cannot yield
-when called through this function.
-
-}
-
-@APIEntry{int lua_closethread (lua_State *L, lua_State *from);|
-@apii{0,?,-}
-
-Resets a thread, cleaning its call stack and closing all pending
-to-be-closed variables.
-The parameter @id{from} represents the coroutine that is resetting @id{L}.
-If there is no such coroutine,
-this parameter can be @id{NULL}.
-
-Unless @id{L} is equal to @id{from},
-the call returns a status code:
-@Lid{LUA_OK} for no errors in the thread
-(either the original error that stopped the thread or
-errors in closing methods),
-or an error status otherwise.
-In case of error,
-the error object is put on the top of the stack.
-
-If @id{L} is equal to @id{from},
-it corresponds to a thread closing itself.
-In that case,
-the call does not return;
-instead, the resume that (re)started the thread returns.
-The thread must be running inside a resume.
-
-}
-
-@APIEntry{int lua_compare (lua_State *L, int index1, int index2, int op);|
-@apii{0,0,e}
-
-Compares two Lua values.
-Returns 1 if the value at index @id{index1} satisfies @id{op}
-when compared with the value at index @id{index2},
-following the semantics of the corresponding Lua operator
-(that is, it may call metamethods).
-Otherwise @N{returns 0}.
-Also @N{returns 0} if any of the indices is not valid.
-
-The value of @id{op} must be one of the following constants:
-@description{
-
-@item{@defid{LUA_OPEQ}| compares for equality (@T{==})}
-@item{@defid{LUA_OPLT}| compares for less than (@T{<})}
-@item{@defid{LUA_OPLE}| compares for less or equal (@T{<=})}
-
-}
-
-}
-
-@APIEntry{void lua_concat (lua_State *L, int n);|
-@apii{n,1,e}
-
-Concatenates the @id{n} values at the top of the stack,
-pops them, and leaves the result on the top.
-If @N{@T{n} is 1}, the result is the single value on the stack
-(that is, the function does nothing);
-if @id{n} is 0, the result is the empty string.
-Concatenation is performed following the usual semantics of Lua
-@see{concat}.
-
-}
-
-@APIEntry{void lua_copy (lua_State *L, int fromidx, int toidx);|
-@apii{0,0,-}
-
-Copies the element at index @id{fromidx}
-into the valid index @id{toidx},
-replacing the value at that position.
-Values at other positions are not affected.
-
-}
-
-@APIEntry{void lua_createtable (lua_State *L, int nseq, int nrec);|
-@apii{0,1,m}
-
-Creates a new empty table and pushes it onto the stack.
-Parameter @id{nseq} is a hint for how many elements the table
-will have as a sequence;
-parameter @id{nrec} is a hint for how many other elements
-the table will have.
-Lua may use these hints to preallocate memory for the new table.
-This preallocation may help performance when you know in advance
-how many elements the table will have.
-Otherwise you should use the function @Lid{lua_newtable}.
-
-}
-
-@APIEntry{int lua_dump (lua_State *L,
- lua_Writer writer,
- void *data,
- int strip);|
-@apii{0,0,-}
-
-Dumps a function as a binary chunk.
-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,
-@Lid{lua_dump} calls function @id{writer} @seeC{lua_Writer}
-with the given @id{data}
-to write them.
-
-The function @Lid{lua_dump} fully preserves the Lua stack
-through the calls to the writer function,
-except that it may push some values for internal use
-before the first call,
-and it restores the stack size to its original size
-after the last call.
-
-If @id{strip} is true,
-the binary representation may not include all debug information
-about the function,
-to save space.
-
-The value returned is the error code returned by the last
-call to the writer;
-@N{0 means} no errors.
-
-}
-
-@APIEntry{int lua_error (lua_State *L);|
-@apii{1,0,v}
-
-Raises a Lua error,
-using the value on the top of the stack as the error object.
-This function does a long jump,
-and therefore never returns
-@seeC{luaL_error}.
-
-}
-
-@APIEntry{int lua_gc (lua_State *L, int what, ...);|
-@apii{0,0,-}
-
-Controls the garbage collector.
-
-This function performs several tasks,
-according to the value of the parameter @id{what}.
-For options that need extra arguments,
-they are listed after the option.
-@description{
-
-@item{@defid{LUA_GCCOLLECT}|
-Performs a full garbage-collection cycle.
-}
-
-@item{@defid{LUA_GCSTOP}|
-Stops the garbage collector.
-}
-
-@item{@defid{LUA_GCRESTART}|
-Restarts the garbage collector.
-}
-
-@item{@defid{LUA_GCCOUNT}|
-Returns the current amount of memory (in Kbytes) in use by Lua.
-}
-
-@item{@defid{LUA_GCCOUNTB}|
-Returns the remainder of dividing the current amount of bytes of
-memory in use by Lua by 1024.
-}
-
-@item{@defid{LUA_GCSTEP} (size_t n)|
-Performs a step of garbage collection.
-}
-
-@item{@defid{LUA_GCISRUNNING}|
-Returns a boolean that tells whether the collector is running
-(i.e., not stopped).
-}
-
-@item{@defid{LUA_GCINC}|
-Changes the collector to incremental mode.
-Returns the previous mode (@id{LUA_GCGEN} or @id{LUA_GCINC}).
-}
-
-@item{@defid{LUA_GCGEN}|
-Changes the collector to generational mode.
-Returns the previous mode (@id{LUA_GCGEN} or @id{LUA_GCINC}).
-}
-
-@item{@defid{LUA_GCPARAM} (int param, int val)|
-Changes and/or returns the value of a parameter of the collector.
-If @id{val} is -1, the call only returns the current value.
-The argument @id{param} must have one of the following values:
-@description{
-@item{@defid{LUA_GCPMINORMUL}| The minor multiplier. }
-@item{@defid{LUA_GCPMAJORMINOR}| The major-minor multiplier. }
-@item{@defid{LUA_GCPMINORMAJOR}| The minor-major multiplier. }
-@item{@defid{LUA_GCPPAUSE}| The garbage-collector pause. }
-@item{@defid{LUA_GCPSTEPMUL}| The step multiplier. }
-@item{@defid{LUA_GCPSTEPSIZE}| The step size. }
-}
-}
-
-}
-
-For more details about these options,
-see @Lid{collectgarbage}.
-
-This function should not be called by a finalizer.
-
-}
-
-@APIEntry{lua_Alloc lua_getallocf (lua_State *L, void **ud);|
-@apii{0,0,-}
-
-Returns the @x{memory-allocator function} of a given state.
-If @id{ud} is not @id{NULL}, Lua stores in @T{*ud} the
-opaque pointer given when the memory-allocator function was set.
-
-}
-
-@APIEntry{int lua_getfield (lua_State *L, int index, const char *k);|
-@apii{0,1,e}
-
-Pushes onto the stack the value @T{t[k]},
-where @id{t} is the value at the given index.
-As in Lua, this function may trigger a metamethod
-for the @Q{index} event @see{metatable}.
-
-Returns the type of the pushed value.
-
-}
-
-@APIEntry{void *lua_getextraspace (lua_State *L);|
-@apii{0,0,-}
-
-Returns a pointer to a raw memory area associated with the
-given Lua state.
-The application can use this area for any purpose;
-Lua does not use it for anything.
-
-Each new thread has this area initialized with a copy
-of the area of the @x{main thread}.
-
-By default, this area has the size of a pointer to void,
-but you can recompile Lua with a different size for this area.
-(See @id{LUA_EXTRASPACE} in @id{luaconf.h}.)
-
-}
-
-@APIEntry{int lua_getglobal (lua_State *L, const char *name);|
-@apii{0,1,e}
-
-Pushes onto the stack the value of the global @id{name}.
-Returns the type of that value.
-
-}
-
-@APIEntry{int lua_geti (lua_State *L, int index, lua_Integer i);|
-@apii{0,1,e}
-
-Pushes onto the stack the value @T{t[i]},
-where @id{t} is the value at the given index.
-As in Lua, this function may trigger a metamethod
-for the @Q{index} event @see{metatable}.
-
-Returns the type of the pushed value.
-
-}
-
-@APIEntry{int lua_getmetatable (lua_State *L, int index);|
-@apii{0,0|1,-}
-
-If the value at the given index has a metatable,
-the function pushes that metatable onto the stack and @N{returns 1}.
-Otherwise,
-the function @N{returns 0} and pushes nothing on the stack.
-
-}
-
-@APIEntry{int lua_gettable (lua_State *L, int index);|
-@apii{1,1,e}
-
-Pushes onto the stack the value @T{t[k]},
-where @id{t} is the value at the given index
-and @id{k} is the value on the top of the stack.
-
-This function pops the key from the stack,
-pushing the resulting value in its place.
-As in Lua, this function may trigger a metamethod
-for the @Q{index} event @see{metatable}.
-
-Returns the type of the pushed value.
-
-}
-
-@APIEntry{int lua_gettop (lua_State *L);|
-@apii{0,0,-}
-
-Returns the index of the top element in the stack.
-Because indices start @N{at 1},
-this result is equal to the number of elements in the stack;
-in particular, @N{0 means} an empty stack.
-
-}
-
-@APIEntry{int lua_getiuservalue (lua_State *L, int index, int n);|
-@apii{0,1,-}
-
-Pushes onto the stack the @id{n}-th user value associated with the
-full userdata at the given index and
-returns the type of the pushed value.
-
-If the userdata does not have that value,
-pushes @nil and returns @Lid{LUA_TNONE}.
-
-}
-
-@APIEntry{void lua_insert (lua_State *L, int index);|
-@apii{1,1,-}
-
-Moves the top element into the given valid index,
-shifting up the elements above this index to open space.
-This function cannot be called with a pseudo-index,
-because a pseudo-index is not an actual stack position.
-
-}
-
-@APIEntry{typedef @ldots lua_Integer;|
-
-The type of integers in Lua.
-
-By default this type is @id{long long},
-(usually a 64-bit two's complement integer),
-but that can be changed to @id{long} or @id{int}
-(usually a 32-bit two's complement integer).
-(See @id{LUA_INT_TYPE} in @id{luaconf.h}.)
-
-Lua also defines the constants
-@defid{LUA_MININTEGER} and @defid{LUA_MAXINTEGER},
-with the minimum and the maximum values that fit in this type.
-
-}
-
-@APIEntry{int lua_isboolean (lua_State *L, int index);|
-@apii{0,0,-}
-
-Returns 1 if the value at the given index is a boolean,
-and @N{0 otherwise}.
-
-}
-
-@APIEntry{int lua_iscfunction (lua_State *L, int index);|
-@apii{0,0,-}
-
-Returns 1 if the value at the given index is a @N{C function},
-and @N{0 otherwise}.
-
-}
-
-@APIEntry{int lua_isfunction (lua_State *L, int index);|
-@apii{0,0,-}
-
-Returns 1 if the value at the given index is a function
-(either C or Lua), and @N{0 otherwise}.
-
-}
-
-@APIEntry{int lua_isinteger (lua_State *L, int index);|
-@apii{0,0,-}
-
-Returns 1 if the value at the given index is an integer
-(that is, the value is a number and is represented as an integer),
-and @N{0 otherwise}.
-
-}
-
-@APIEntry{int lua_islightuserdata (lua_State *L, int index);|
-@apii{0,0,-}
-
-Returns 1 if the value at the given index is a light userdata,
-and @N{0 otherwise}.
-
-}
-
-@APIEntry{int lua_isnil (lua_State *L, int index);|
-@apii{0,0,-}
-
-Returns 1 if the value at the given index is @nil,
-and @N{0 otherwise}.
-
-}
-
-@APIEntry{int lua_isnone (lua_State *L, int index);|
-@apii{0,0,-}
-
-Returns 1 if the given index is not valid,
-and @N{0 otherwise}.
-
-}
-
-@APIEntry{int lua_isnoneornil (lua_State *L, int index);|
-@apii{0,0,-}
-
-Returns 1 if the given index is not valid
-or if the value at this index is @nil,
-and @N{0 otherwise}.
-
-}
-
-@APIEntry{int lua_isnumber (lua_State *L, int index);|
-@apii{0,0,-}
-
-Returns 1 if the value at the given index is a number
-or a string convertible to a number,
-and @N{0 otherwise}.
-
-}
-
-@APIEntry{int lua_isstring (lua_State *L, int index);|
-@apii{0,0,-}
-
-Returns 1 if the value at the given index is a string
-or a number (which is always convertible to a string),
-and @N{0 otherwise}.
-
-}
-
-@APIEntry{int lua_istable (lua_State *L, int index);|
-@apii{0,0,-}
-
-Returns 1 if the value at the given index is a table,
-and @N{0 otherwise}.
-
-}
-
-@APIEntry{int lua_isthread (lua_State *L, int index);|
-@apii{0,0,-}
-
-Returns 1 if the value at the given index is a thread,
-and @N{0 otherwise}.
-
-}
-
-@APIEntry{int lua_isuserdata (lua_State *L, int index);|
-@apii{0,0,-}
-
-Returns 1 if the value at the given index is a userdata
-(either full or light), and @N{0 otherwise}.
-
-}
-
-@APIEntry{int lua_isyieldable (lua_State *L);|
-@apii{0,0,-}
-
-Returns 1 if the given coroutine can yield,
-and @N{0 otherwise}.
-
-}
-
-@APIEntry{typedef @ldots lua_KContext;|
-
-The type for continuation-function contexts.
-It must be a numeric type.
-This type is defined as @id{intptr_t}
-when @id{intptr_t} is available,
-so that it can store pointers too.
-Otherwise, it is defined as @id{ptrdiff_t}.
-
-}
-
-@APIEntry{
-typedef int (*lua_KFunction) (lua_State *L, int status, lua_KContext ctx);|
-
-Type for continuation functions @see{continuations}.
-
-}
-
-@APIEntry{void lua_len (lua_State *L, int index);|
-@apii{0,1,e}
-
-Returns the length of the value at the given index.
-It is equivalent to the @Char{#} operator in Lua @see{len-op} and
-may trigger a metamethod for the @Q{length} event @see{metatable}.
-The result is pushed on the stack.
-
-}
-
-@APIEntry{
-int lua_load (lua_State *L,
- lua_Reader reader,
- void *data,
- const char *chunkname,
- const char *mode);|
-@apii{0,1,-}
-
-Loads a Lua chunk without running it.
-If there are no errors,
-@id{lua_load} pushes the compiled chunk as a Lua
-function on top of the stack.
-Otherwise, it pushes an error message.
-
-The @id{lua_load} function uses a user-supplied @id{reader} function
-to read the chunk @seeC{lua_Reader}.
-The @id{data} argument is an opaque value passed to the reader function.
-
-The @id{chunkname} argument gives a name to the chunk,
-which is used for error messages and in debug information @see{debugI}.
-
-@id{lua_load} automatically detects whether the chunk is text or binary
-and loads it accordingly (see program @idx{luac}).
-The string @id{mode} works as in function @Lid{load},
-with the addition that
-a @id{NULL} value is equivalent to the string @St{bt}.
-Moreover, it may have a @Char{B} instead of a @Char{b},
-meaning a @emphx{fixed buffer} with the binary dump.
-
-A fixed buffer means that the address returned by the reader function
-will contain the chunk until everything created by the chunk has
-been collected;
-therefore, Lua can avoid copying to internal structures
-some parts of the chunk.
-(In general, a fixed buffer would keep its contents
-until the end of the program,
-for instance with the chunk in ROM.)
-Moreover, for a fixed buffer,
-the reader function should return the entire chunk in the first read.
-(As an example, @Lid{luaL_loadbufferx} does that,
-which means that you can use it to load fixed buffers.)
-
-The function @Lid{lua_load} fully preserves the Lua stack
-through the calls to the reader function,
-except that it may push some values for internal use
-before the first call,
-and it restores the stack size to its original size plus one
-(for the pushed result) after the last call.
-
-@id{lua_load} can return
-@Lid{LUA_OK}, @Lid{LUA_ERRSYNTAX}, or @Lid{LUA_ERRMEM}.
-The function may also return other values corresponding to
-errors raised by the read function @see{statuscodes}.
-
-If the resulting function has upvalues,
-its first upvalue is set to the value of the @x{global environment}
-stored at index @id{LUA_RIDX_GLOBALS} in the registry @see{registry}.
-When loading main chunks,
-this upvalue will be the @id{_ENV} variable @see{globalenv}.
-Other upvalues are initialized with @nil.
-
-}
-
-@APIEntry{lua_State *lua_newstate (lua_Alloc f, void *ud,
- unsigned int seed);|
-@apii{0,0,-}
-
-Creates a new independent state and returns its main thread.
-Returns @id{NULL} if it cannot create the state
-(due to lack of memory).
-The argument @id{f} is the @x{allocator function};
-Lua will do all memory allocation for this state
-through this function @seeF{lua_Alloc}.
-The second argument, @id{ud}, is an opaque pointer that Lua
-passes to the allocator in every call.
-The third argument, @id{seed},
-is a seed for the hashing of strings.
-
-}
-
-@APIEntry{void lua_newtable (lua_State *L);|
-@apii{0,1,m}
-
-Creates a new empty table and pushes it onto the stack.
-It is equivalent to @T{lua_createtable(L,0,0)}.
-
-}
-
-@APIEntry{lua_State *lua_newthread (lua_State *L);|
-@apii{0,1,m}
-
-Creates a new thread, pushes it on the stack,
-and returns a pointer to a @Lid{lua_State} that represents this new thread.
-The new thread returned by this function shares with the original thread
-its global environment,
-but has an independent execution stack.
-
-Threads are subject to garbage collection,
-like any Lua object.
-
-}
-
-@APIEntry{void *lua_newuserdatauv (lua_State *L, size_t size, int nuvalue);|
-@apii{0,1,m}
-
-This function creates and pushes on the stack a new full userdata,
-with @id{nuvalue} associated Lua values, called @id{user values},
-plus an associated block of raw memory with @id{size} bytes.
-
-The user values can be set and read with the functions
-@Lid{lua_setiuservalue} and @Lid{lua_getiuservalue}.
-The block of memory is suitably aligned for any @N{ISO C} object.
-(See macro @id{LUAI_MAXALIGN} in file @id{luaconf.h} for other
-alignment requirements.)
-
-The function returns the address of the block of memory.
-Lua ensures that this address is valid as long as
-the corresponding userdata is alive @see{GC}.
-Moreover, if the userdata is marked for finalization @see{finalizers},
-its address is valid at least until the call to its finalizer.
-
-}
-
-@APIEntry{int lua_next (lua_State *L, int index);|
-@apii{1,2|0,v}
-
-Pops a key from the stack,
-and pushes a key@En{}value pair from the table at the given index,
-the @Q{next} pair after the given key.
-If there are no more elements in the table,
-then @Lid{lua_next} @N{returns 0} and pushes nothing.
-
-A typical table traversal looks like this:
-@verbatim{
-/* table is in the stack at index 't' */
-lua_pushnil(L); /* first key */
-while (lua_next(L, t) != 0) {
- /* uses 'key' (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)));
- /* removes 'value'; keeps 'key' for next iteration */
- lua_pop(L, 1);
-}
-}
-
-While traversing a table,
-avoid calling @Lid{lua_tolstring} directly on a key,
-unless you know that the key is actually a string.
-Recall that @Lid{lua_tolstring} may change
-the value at the given index;
-this confuses the next call to @Lid{lua_next}.
-
-This function may raise an error if the given key
-is neither @nil nor present in the table.
-See function @Lid{next} for the caveats of modifying
-the table during its traversal.
-
-}
-
-@APIEntry{typedef @ldots lua_Number;|
-
-The type of floats in Lua.
-
-By default this type is double,
-but that can be changed to a single float or a long double.
-(See @id{LUA_FLOAT_TYPE} in @id{luaconf.h}.)
-
-}
-
-@APIEntry{int lua_numbertointeger (lua_Number n, lua_Integer *p);|
-
-Tries to convert a Lua float to a Lua integer;
-the float @id{n} must have an integral value.
-If that value is within the range of Lua integers,
-it is converted to an integer and assigned to @T{*p}.
-The macro results in a boolean indicating whether the
-conversion was successful.
-(Note that this range test can be tricky to do
-correctly without this macro, due to rounding.)
-
-This macro may evaluate its arguments more than once.
-
-}
-
-@APIEntry{unsigned lua_numbertocstring (lua_State *L, int idx,
- char *buff);|
-@apii{0,0,-}
-
-Converts the number at acceptable index @id{idx} to a string
-and puts the result in @id{buff}.
-The buffer must have a size of at least @defid{LUA_N2SBUFFSZ} bytes.
-The conversion follows a non-specified format @see{coercion}.
-The function returns the number of bytes written to the buffer
-(including the final zero),
-or zero if the value at @id{idx} is not a number.
-
-}
-
-@APIEntry{int lua_pcall (lua_State *L, int nargs, int nresults, int msgh);|
-@apii{nargs + 1,nresults|1,-}
-
-Calls a function (or a callable object) in protected mode.
-
-Both @id{nargs} and @id{nresults} have the same meaning as
-in @Lid{lua_call}.
-If there are no errors during the call,
-@Lid{lua_pcall} behaves exactly like @Lid{lua_call}.
-However, if there is any error,
-@Lid{lua_pcall} catches it,
-pushes a single value on the stack (the error object),
-and returns an error code.
-Like @Lid{lua_call},
-@Lid{lua_pcall} always removes the function
-and its arguments from the stack.
-
-If @id{msgh} is 0,
-then the error object returned on the stack
-is exactly the original error object.
-Otherwise, @id{msgh} is the stack index of a
-@emph{message handler}.
-(This index cannot be a pseudo-index.)
-In case of runtime errors,
-this handler will be called with the error object
-and its return value will be the object
-returned on the stack by @Lid{lua_pcall}.
-
-Typically, the message handler is used to add more debug
-information to the error object, such as a stack traceback.
-Such information cannot be gathered after the return of @Lid{lua_pcall},
-since by then the stack has unwound.
-
-The @Lid{lua_pcall} function returns one of the following status codes:
-@Lid{LUA_OK}, @Lid{LUA_ERRRUN}, @Lid{LUA_ERRMEM}, or @Lid{LUA_ERRERR}.
-
-}
-
-@APIEntry{
-int lua_pcallk (lua_State *L,
- int nargs,
- int nresults,
- int msgh,
- lua_KContext ctx,
- lua_KFunction k);|
-@apii{nargs + 1,nresults|1,-}
-
-This function behaves exactly like @Lid{lua_pcall},
-except that it allows the called function to yield @see{continuations}.
-
-}
-
-@APIEntry{void lua_pop (lua_State *L, int n);|
-@apii{n,0,e}
-
-Pops @id{n} elements from the stack.
-It is implemented as a macro over @Lid{lua_settop}.
-
-}
-
-@APIEntry{void lua_pushboolean (lua_State *L, int b);|
-@apii{0,1,-}
-
-Pushes a boolean value with value @id{b} onto the stack.
-
-}
-
-@APIEntry{void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n);|
-@apii{n,1,m}
-
-Pushes a new @N{C closure} onto the stack.
-This function receives a pointer to a @N{C function}
-and pushes onto the stack a Lua value of type @id{function} that,
-when called, invokes the corresponding @N{C function}.
-The parameter @id{n} tells how many upvalues this function will have
-@see{c-closure}.
-
-Any function to be callable by Lua must
-follow the correct protocol to receive its parameters
-and return its results @seeC{lua_CFunction}.
-
-When a @N{C function} is created,
-it is possible to associate some values with it,
-the so called upvalues;
-these upvalues are then accessible to the function whenever it is called.
-This association is called a @x{@N{C closure}} @see{c-closure}.
-To create a @N{C closure},
-first the initial values for its upvalues must be pushed onto the stack.
-(When there are multiple upvalues, the first value is pushed first.)
-Then @Lid{lua_pushcclosure}
-is called to create and push the @N{C function} onto the stack,
-with the argument @id{n} telling how many values will be
-associated with the function.
-@Lid{lua_pushcclosure} also pops these values from the stack.
-
-The maximum value for @id{n} is 255.
-
-When @id{n} is zero,
-this function creates a @def{light @N{C function}},
-which is just a pointer to the @N{C function}.
-In that case, it never raises a memory error.
-
-}
-
-@APIEntry{void lua_pushcfunction (lua_State *L, lua_CFunction f);|
-@apii{0,1,-}
-
-Pushes a @N{C function} onto the stack.
-This function is equivalent to @Lid{lua_pushcclosure} with no upvalues.
-
-}
-
-@APIEntry{const char *lua_pushexternalstring (lua_State *L,
- const char *s, size_t len, lua_Alloc falloc, void *ud);|
-@apii{0,1,m}
-
-Creates an @emphx{external string},
-that is, a string that uses memory not managed by Lua.
-The pointer @id{s} points to the external buffer
-holding the string content,
-and @id{len} is the length of the string.
-The string should have a zero at its end,
-that is, the condition @T{s[len] == '\0'} should hold.
-As with any string in Lua,
-the length must fit in a Lua integer.
-
-If @id{falloc} is different from @id{NULL},
-that function will be called by Lua
-when the external buffer is no longer needed.
-The contents of the buffer should not change before this call.
-The function will be called with the given @id{ud},
-the string @id{s} as the block,
-the length plus one (to account for the ending zero) as the old size,
-and 0 as the new size.
-
-Even when using an external buffer,
-Lua still has to allocate a header for the string.
-In case of a memory-allocation error,
-Lua will call @id{falloc} before raising the error.
-
-The function returns a pointer to the string (that is, @id{s}).
-
-}
-
-
-@APIEntry{const char *lua_pushfstring (lua_State *L, const char *fmt, ...);|
-@apii{0,1,v}
-
-Pushes onto the stack a formatted string
-and returns a pointer to this string @see{constchar}.
-The result is a copy of @id{fmt} with
-each @emph{conversion specifier} replaced by a string representation
-of its respective extra argument.
-A conversion specifier (and its corresponding extra argument) can be
-@Char{%%} (inserts the character @Char{%}),
-@Char{%s} (inserts a zero-terminated string, with no size restrictions),
-@Char{%f} (inserts a @Lid{lua_Number}),
-@Char{%I} (inserts a @Lid{lua_Integer}),
-@Char{%p} (inserts a void pointer),
-@Char{%d} (inserts an @T{int}),
-@Char{%c} (inserts an @T{int} as a one-byte character), and
-@Char{%U} (inserts an @T{unsigned long} as a @x{UTF-8} byte sequence).
-
-Every occurrence of @Char{%} in the string @id{fmt}
-must form a valid conversion specifier.
-
-Besides memory allocation errors,
-this function may raise an error if the resulting string is too large.
-
-}
-
-@APIEntry{void lua_pushglobaltable (lua_State *L);|
-@apii{0,1,-}
-
-Pushes the @x{global environment} onto the stack.
-
-}
-
-@APIEntry{void lua_pushinteger (lua_State *L, lua_Integer n);|
-@apii{0,1,-}
-
-Pushes an integer with value @id{n} onto the stack.
-
-}
-
-@APIEntry{void lua_pushlightuserdata (lua_State *L, void *p);|
-@apii{0,1,-}
-
-Pushes a light userdata onto the stack.
-
-Userdata represent @N{C values} in Lua.
-A @def{light userdata} represents a pointer, a @T{void*}.
-It is a value (like a number):
-you do not create it, it has no individual metatable,
-and it is not collected (as it was never created).
-A light userdata is equal to @Q{any}
-light userdata with the same @N{C address}.
-
-}
-
-@APIEntry{const char *lua_pushliteral (lua_State *L, const char *s);|
-@apii{0,1,v}
-
-This macro is equivalent to @Lid{lua_pushstring},
-but should be used only when @id{s} is a literal string.
-(Lua may optimize this case.)
-
-}
-
-@APIEntry{const char *lua_pushlstring (lua_State *L, const char *s, size_t len);|
-@apii{0,1,v}
-
-Pushes the string pointed to by @id{s} with size @id{len}
-onto the stack.
-Lua will make or reuse an internal copy of the given string,
-so the memory at @id{s} can be freed or reused immediately after
-the function returns.
-The string can contain any binary data,
-including @x{embedded zeros}.
-
-Returns a pointer to the internal copy of the string @see{constchar}.
-
-Besides memory allocation errors,
-this function may raise an error if the string is too large.
-
-}
-
-@APIEntry{void lua_pushnil (lua_State *L);|
-@apii{0,1,-}
-
-Pushes a nil value onto the stack.
-
-}
-
-@APIEntry{void lua_pushnumber (lua_State *L, lua_Number n);|
-@apii{0,1,-}
-
-Pushes a float with value @id{n} onto the stack.
-
-}
-
-@APIEntry{const char *lua_pushstring (lua_State *L, const char *s);|
-@apii{0,1,m}
-
-Pushes the zero-terminated string pointed to by @id{s}
-onto the stack.
-Lua will make or reuse an internal copy of the given string,
-so the memory at @id{s} can be freed or reused immediately after
-the function returns.
-
-Returns a pointer to the internal copy of the string @see{constchar}.
-
-If @id{s} is @id{NULL}, pushes @nil and returns @id{NULL}.
-
-}
-
-@APIEntry{int lua_pushthread (lua_State *L);|
-@apii{0,1,-}
-
-Pushes the thread represented by @id{L} onto the stack.
-Returns 1 if this thread is the @x{main thread} of its state.
-
-}
-
-@APIEntry{void lua_pushvalue (lua_State *L, int index);|
-@apii{0,1,-}
-
-Pushes a copy of the element at the given index
-onto the stack.
-
-}
-
-@APIEntry{
-const char *lua_pushvfstring (lua_State *L,
- const char *fmt,
- va_list argp);|
-@apii{0,1,-}
-
-Equivalent to @Lid{lua_pushfstring},
-except that it receives a @id{va_list}
-instead of a variable number of arguments,
-and it does not raise errors.
-Instead, in case of errors it pushes the error message
-and returns @id{NULL}.
-
-}
-
-@APIEntry{int lua_rawequal (lua_State *L, int index1, int index2);|
-@apii{0,0,-}
-
-Returns 1 if the two values in indices @id{index1} and
-@id{index2} are primitively equal
-(that is, equal without calling the @idx{__eq} metamethod).
-Otherwise @N{returns 0}.
-Also @N{returns 0} if any of the indices are not valid.
-
-}
-
-@APIEntry{int lua_rawget (lua_State *L, int index);|
-@apii{1,1,-}
-
-Similar to @Lid{lua_gettable}, but does a raw access
-(i.e., without metamethods).
-The value at @id{index} must be a table.
-
-}
-
-@APIEntry{int lua_rawgeti (lua_State *L, int index, lua_Integer n);|
-@apii{0,1,-}
-
-Pushes onto the stack the value @T{t[n]},
-where @id{t} is the table at the given index.
-The access is raw,
-that is, it does not use the @idx{__index} metavalue.
-
-Returns the type of the pushed value.
-
-}
-
-@APIEntry{int lua_rawgetp (lua_State *L, int index, const void *p);|
-@apii{0,1,-}
-
-Pushes onto the stack the value @T{t[k]},
-where @id{t} is the table at the given index and
-@id{k} is the pointer @id{p} represented as a light userdata.
-The access is raw;
-that is, it does not use the @idx{__index} metavalue.
-
-Returns the type of the pushed value.
-
-}
-
-@APIEntry{lua_Unsigned lua_rawlen (lua_State *L, int index);|
-@apii{0,0,-}
-
-Returns the raw @Q{length} of the value at the given index:
-for strings, this is the string length;
-for tables, this is the result of the length operator (@Char{#})
-with no metamethods;
-for userdata, this is the size of the block of memory allocated
-for the userdata.
-For other values, this call @N{returns 0}.
-
-}
-
-@APIEntry{void lua_rawset (lua_State *L, int index);|
-@apii{2,0,m}
-
-Similar to @Lid{lua_settable}, but does a raw assignment
-(i.e., without metamethods).
-The value at @id{index} must be a table.
-
-}
-
-@APIEntry{void lua_rawseti (lua_State *L, int index, lua_Integer i);|
-@apii{1,0,m}
-
-Does the equivalent of @T{t[i] = v},
-where @id{t} is the table at the given index
-and @id{v} is the value on the top of the stack.
-
-This function pops the value from the stack.
-The assignment is raw,
-that is, it does not use the @idx{__newindex} metavalue.
-
-}
-
-@APIEntry{void lua_rawsetp (lua_State *L, int index, const void *p);|
-@apii{1,0,m}
-
-Does the equivalent of @T{t[p] = v},
-where @id{t} is the table at the given index,
-@id{p} is encoded as a light userdata,
-and @id{v} is the value on the top of the stack.
-
-This function pops the value from the stack.
-The assignment is raw,
-that is, it does not use the @idx{__newindex} metavalue.
-
-}
-
-@APIEntry{
-typedef const char * (*lua_Reader) (lua_State *L,
- void *data,
- size_t *size);|
-
-The reader function used by @Lid{lua_load}.
-Every time @Lid{lua_load} needs another piece of the chunk,
-it calls the reader,
-passing along its @id{data} parameter.
-The reader must return a pointer to a block of memory
-with a new piece of the chunk
-and set @id{size} to the block size.
-The block must exist until the reader function is called again.
-To signal the end of the chunk,
-the reader must return @id{NULL} or set @id{size} to zero.
-The reader function may return pieces of any size greater than zero.
-
-}
-
-@APIEntry{void lua_register (lua_State *L, const char *name, lua_CFunction f);|
-@apii{0,0,e}
-
-Sets the @N{C function} @id{f} as the new value of global @id{name}.
-It is defined as a macro:
-@verbatim{
-#define lua_register(L,n,f) \
- (lua_pushcfunction(L, f), lua_setglobal(L, n))
-}
-
-}
-
-@APIEntry{void lua_remove (lua_State *L, int index);|
-@apii{1,0,-}
-
-Removes the element at the given valid index,
-shifting down the elements above this index to fill the gap.
-This function cannot be called with a pseudo-index,
-because a pseudo-index is not an actual stack position.
-
-}
-
-@APIEntry{void lua_replace (lua_State *L, int index);|
-@apii{1,0,-}
-
-Moves the top element into the given valid index
-without shifting any element
-(therefore replacing the value at that given index),
-and then pops the top element.
-
-}
-
-
-@APIEntry{int lua_resume (lua_State *L, lua_State *from, int nargs,
- int *nresults);|
-@apii{?,?,-}
-
-Starts and resumes a coroutine in the given thread @id{L}.
-
-To start a coroutine,
-you push the main function plus any arguments
-onto the empty stack of the thread.
-then you call @Lid{lua_resume},
-with @id{nargs} being the number of arguments.
-The function returns when the coroutine suspends,
-finishes its execution, or raises an unprotected error.
-When it returns without errors,
-@id{*nresults} is updated and
-the top of the stack contains
-the @id{*nresults} values passed to @Lid{lua_yield}
-or returned by the body function.
-@Lid{lua_resume} returns
-@Lid{LUA_YIELD} if the coroutine yields,
-@Lid{LUA_OK} if the coroutine finishes its execution
-without errors,
-or an error code in case of errors @see{statuscodes}.
-In case of errors,
-the error object is pushed on the top of the stack.
-(In that case, @id{nresults} is not updated,
-as its value would have to be 1 for the sole error object.)
-
-To resume a suspended coroutine,
-you remove the @id{*nresults} yielded values from its stack,
-push the values to be passed as results from @id{yield},
-and then call @Lid{lua_resume}.
-
-The parameter @id{from} represents the coroutine that is resuming @id{L}.
-If there is no such coroutine,
-this parameter can be @id{NULL}.
-
-}
-
-@APIEntry{void lua_rotate (lua_State *L, int idx, int n);|
-@apii{0,0,-}
-
-Rotates the stack elements between the valid index @id{idx}
-and the top of the stack.
-The elements are rotated @id{n} positions in the direction of the top,
-for a positive @id{n},
-or @T{-n} positions in the direction of the bottom,
-for a negative @id{n}.
-The absolute value of @id{n} must not be greater than the size
-of the slice being rotated.
-This function cannot be called with a pseudo-index,
-because a pseudo-index is not an actual stack position.
-
-}
-
-@APIEntry{void lua_setallocf (lua_State *L, lua_Alloc f, void *ud);|
-@apii{0,0,-}
-
-Changes the @x{allocator function} of a given state to @id{f}
-with user data @id{ud}.
-
-}
-
-@APIEntry{void lua_setfield (lua_State *L, int index, const char *k);|
-@apii{1,0,e}
-
-Does the equivalent to @T{t[k] = v},
-where @id{t} is the value at the given index
-and @id{v} is the value on the top of the stack.
-
-This function pops the value from the stack.
-As in Lua, this function may trigger a metamethod
-for the @Q{newindex} event @see{metatable}.
-
-}
-
-@APIEntry{void lua_setglobal (lua_State *L, const char *name);|
-@apii{1,0,e}
-
-Pops a value from the stack and
-sets it as the new value of global @id{name}.
-
-}
-
-@APIEntry{void lua_seti (lua_State *L, int index, lua_Integer n);|
-@apii{1,0,e}
-
-Does the equivalent to @T{t[n] = v},
-where @id{t} is the value at the given index
-and @id{v} is the value on the top of the stack.
-
-This function pops the value from the stack.
-As in Lua, this function may trigger a metamethod
-for the @Q{newindex} event @see{metatable}.
-
-}
-
-@APIEntry{int lua_setiuservalue (lua_State *L, int index, int n);|
-@apii{1,0,-}
-
-Pops a value from the stack and sets it as
-the new @id{n}-th user value associated to the
-full userdata at the given index.
-Returns 0 if the userdata does not have that value.
-
-}
-
-@APIEntry{int lua_setmetatable (lua_State *L, int index);|
-@apii{1,0,-}
-
-Pops a table or @nil from the stack and
-sets that value as the new metatable for the value at the given index.
-(@nil means no metatable.)
-
-(For historical reasons, this function returns an @id{int},
-which now is always 1.)
-
-}
-
-@APIEntry{void lua_settable (lua_State *L, int index);|
-@apii{2,0,e}
-
-Does the equivalent to @T{t[k] = v},
-where @id{t} is the value at the given index,
-@id{v} is the value on the top of the stack,
-and @id{k} is the value just below the top.
-
-This function pops both the key and the value from the stack.
-As in Lua, this function may trigger a metamethod
-for the @Q{newindex} event @see{metatable}.
-
-}
-
-@APIEntry{void lua_settop (lua_State *L, int index);|
-@apii{?,?,e}
-
-Receives any acceptable stack index, @N{or 0},
-and sets the stack top to this index.
-If the new top is greater than the old one,
-then the new elements are filled with @nil.
-If @id{index} @N{is 0}, then all stack elements are removed.
-
-This function can run arbitrary code when removing an index
-marked as to-be-closed from the stack.
-
-}
-
-@APIEntry{void lua_setwarnf (lua_State *L, lua_WarnFunction f, void *ud);|
-@apii{0,0,-}
-
-Sets the @x{warning function} to be used by Lua to emit warnings
-@see{lua_WarnFunction}.
-The @id{ud} parameter sets the value @id{ud} passed to
-the warning function.
-
-}
-
-@APIEntry{typedef struct lua_State lua_State;|
-
-An opaque structure that points to a thread and indirectly
-(through the thread) to the whole state of a Lua interpreter.
-The Lua library is fully reentrant:
-it has no global variables.
-All information about a state is accessible through this structure.
-
-A pointer to this structure must be passed as the first argument to
-every function in the library, except to @Lid{lua_newstate},
-which creates a Lua state from scratch.
-
-}
-
-@APIEntry{int lua_status (lua_State *L);|
-@apii{0,0,-}
-
-Returns the status of the thread @id{L}.
-
-The status can be @Lid{LUA_OK} for a normal thread,
-an error code if the thread finished the execution
-of a @Lid{lua_resume} with an error,
-or @Lid{LUA_YIELD} if the thread is suspended.
-
-You can call functions only in threads with status @Lid{LUA_OK}.
-You can resume threads with status @Lid{LUA_OK}
-(to start a new coroutine) or @Lid{LUA_YIELD}
-(to resume a coroutine).
-
-}
-
-@APIEntry{size_t lua_stringtonumber (lua_State *L, const char *s);|
-@apii{0,1,-}
-
-Converts the zero-terminated string @id{s} to a number,
-pushes that number into the stack,
-and returns the total size of the string,
-that is, its length plus one.
-The conversion can result in an integer or a float,
-according to the lexical conventions of Lua @see{lexical}.
-The string may have leading and trailing whitespaces and a sign.
-If the string is not a valid numeral,
-returns 0 and pushes nothing.
-(Note that the result can be used as a boolean,
-true if the conversion succeeds.)
-
-}
-
-@APIEntry{int lua_toboolean (lua_State *L, int index);|
-@apii{0,0,-}
-
-Converts the Lua value at the given index to a @N{C boolean}
-value (@N{0 or 1}).
-Like all tests in Lua,
-@Lid{lua_toboolean} returns true for any Lua value
-different from @false and @nil;
-otherwise it returns false.
-(If you want to accept only actual boolean values,
-use @Lid{lua_isboolean} to test the value's type.)
-
-}
-
-@APIEntry{lua_CFunction lua_tocfunction (lua_State *L, int index);|
-@apii{0,0,-}
-
-Converts a value at the given index to a @N{C function}.
-That value must be a @N{C function};
-otherwise, returns @id{NULL}.
-
-}
-
-@APIEntry{void lua_toclose (lua_State *L, int index);|
-@apii{0,0,v}
-
-Marks the given index in the stack as a
-to-be-closed slot @see{to-be-closed}.
-Like a to-be-closed variable in Lua,
-the value at that slot in the stack will be closed
-when it goes out of scope.
-Here, in the context of a C function,
-to go out of scope means that the running function returns to Lua,
-or there is an error,
-or the slot is removed from the stack through
-@Lid{lua_settop} or @Lid{lua_pop},
-or there is a call to @Lid{lua_closeslot}.
-A slot marked as to-be-closed should not be removed from the stack
-by any other function in the API except @Lid{lua_settop} or @Lid{lua_pop},
-unless previously deactivated by @Lid{lua_closeslot}.
-
-This function raises an error if the value at the given slot
-neither has a @idx{__close} metamethod nor is a false value.
-
-This function should not be called for an index
-that is equal to or below an active to-be-closed slot.
-
-Note that, both in case of errors and of a regular return,
-by the time the @idx{__close} metamethod runs,
-the @N{C stack} was already unwound,
-so that any automatic @N{C variable} declared in the calling function
-(e.g., a buffer) will be out of scope.
-
-}
-
-@APIEntry{lua_Integer lua_tointeger (lua_State *L, int index);|
-@apii{0,0,-}
-
-Equivalent to @Lid{lua_tointegerx} with @id{isnum} equal to @id{NULL}.
-
-}
-
-@APIEntry{lua_Integer lua_tointegerx (lua_State *L, int index, int *isnum);|
-@apii{0,0,-}
-
-Converts the Lua value at the given index
-to the signed integral type @Lid{lua_Integer}.
-The Lua value must be an integer,
-or a number or string convertible to an integer @see{coercion};
-otherwise, @id{lua_tointegerx} @N{returns 0}.
-
-If @id{isnum} is not @id{NULL},
-its referent is assigned a boolean value that
-indicates whether the operation succeeded.
-
-}
-
-@APIEntry{const char *lua_tolstring (lua_State *L, int index, size_t *len);|
-@apii{0,0,m}
-
-Converts the Lua value at the given index to a @N{C string}.
-The Lua value must be a string or a number;
-otherwise, the function returns @id{NULL}.
-If the value is a number,
-then @id{lua_tolstring} also
-@emph{changes the actual value in the stack to a string}.
-(This change confuses @Lid{lua_next}
-when @id{lua_tolstring} is applied to keys during a table traversal.)
-
-If @id{len} is not @id{NULL},
-the function sets @T{*len} with the string length.
-The returned @N{C string} always has a zero (@Char{\0})
-after its last character,
-but can contain other zeros in its body.
-
-The pointer returned by @id{lua_tolstring}
-may be invalidated by the garbage collector if the
-corresponding Lua value is removed from the stack @see{constchar}.
-
-This function can raise memory errors only
-when converting a number to a string
-(as then it may create a new string).
-
-}
-
-@APIEntry{lua_Number lua_tonumber (lua_State *L, int index);|
-@apii{0,0,-}
-
-Equivalent to @Lid{lua_tonumberx} with @id{isnum} equal to @id{NULL}.
-
-}
-
-@APIEntry{lua_Number lua_tonumberx (lua_State *L, int index, int *isnum);|
-@apii{0,0,-}
-
-Converts the Lua value at the given index
-to the @N{C type} @Lid{lua_Number} @seeC{lua_Number}.
-The Lua value must be a number or a string convertible to a number
-@see{coercion};
-otherwise, @Lid{lua_tonumberx} @N{returns 0}.
-
-If @id{isnum} is not @id{NULL},
-its referent is assigned a boolean value that
-indicates whether the operation succeeded.
-
-}
-
-@APIEntry{const void *lua_topointer (lua_State *L, int index);|
-@apii{0,0,-}
-
-Converts the value at the given index to a generic
-@N{C pointer} (@T{void*}).
-The value can be a userdata, a table, a thread, a string, or a function;
-otherwise, @id{lua_topointer} returns @id{NULL}.
-Different objects will give different pointers.
-There is no way to convert the pointer back to its original value.
-
-Typically this function is used only for hashing and debug information.
-
-}
-
-@APIEntry{const char *lua_tostring (lua_State *L, int index);|
-@apii{0,0,m}
-
-Equivalent to @Lid{lua_tolstring} with @id{len} equal to @id{NULL}.
-
-}
-
-@APIEntry{lua_State *lua_tothread (lua_State *L, int index);|
-@apii{0,0,-}
-
-Converts the value at the given index to a Lua thread
-(represented as @T{lua_State*}).
-This value must be a thread;
-otherwise, the function returns @id{NULL}.
-
-}
-
-@APIEntry{void *lua_touserdata (lua_State *L, int index);|
-@apii{0,0,-}
-
-If the value at the given index is a full userdata,
-returns its memory-block address.
-If the value is a light userdata,
-returns its value (a pointer).
-Otherwise, returns @id{NULL}.
-
-}
-
-@APIEntry{int lua_type (lua_State *L, int index);|
-@apii{0,0,-}
-
-Returns the type of the value in the given valid index,
-or @id{LUA_TNONE} for a non-valid but acceptable index.
-The types returned by @Lid{lua_type} are coded by the following constants
-defined in @id{lua.h}:
-@defid{LUA_TNIL},
-@defid{LUA_TNUMBER},
-@defid{LUA_TBOOLEAN},
-@defid{LUA_TSTRING},
-@defid{LUA_TTABLE},
-@defid{LUA_TFUNCTION},
-@defid{LUA_TUSERDATA},
-@defid{LUA_TTHREAD},
-and
-@defid{LUA_TLIGHTUSERDATA}.
-
-}
-
-@APIEntry{const char *lua_typename (lua_State *L, int tp);|
-@apii{0,0,-}
-
-Returns the name of the type encoded by the value @id{tp},
-which must be one the values returned by @Lid{lua_type}.
-
-}
-
-@APIEntry{typedef @ldots lua_Unsigned;|
-
-The unsigned version of @Lid{lua_Integer}.
-
-}
-
-@APIEntry{int lua_upvalueindex (int i);|
-@apii{0,0,-}
-
-Returns the pseudo-index that represents the @id{i}-th upvalue of
-the running function @see{c-closure}.
-@id{i} must be in the range @M{[1,256]}.
-
-}
-
-@APIEntry{lua_Number lua_version (lua_State *L);|
-@apii{0,0,-}
-
-Returns the version number of this core.
-
-}
-
-@APIEntry{
-typedef void (*lua_WarnFunction) (void *ud, const char *msg, int tocont);|
-
-The type of @x{warning function}s, called by Lua to emit warnings.
-The first parameter is an opaque pointer
-set by @Lid{lua_setwarnf}.
-The second parameter is the warning message.
-The third parameter is a boolean that
-indicates whether the message is
-to be continued by the message in the next call.
-
-See @Lid{warn} for more details about warnings.
-
-}
-
-@APIEntry{
-void lua_warning (lua_State *L, const char *msg, int tocont);|
-@apii{0,0,-}
-
-Emits a warning with the given message.
-A message in a call with @id{tocont} true should be
-continued in another call to this function.
-
-See @Lid{warn} for more details about warnings.
-
-}
-
-@APIEntry{
-typedef int (*lua_Writer) (lua_State *L,
- const void* p,
- size_t sz,
- void* ud);|
-
-The type of the writer function used by @Lid{lua_dump}.
-Every time @Lid{lua_dump} produces another piece of chunk,
-it calls the writer,
-passing along the buffer to be written (@id{p}),
-its size (@id{sz}),
-and the @id{ud} parameter supplied to @Lid{lua_dump}.
-
-After @Lid{lua_dump} writes its last piece,
-it will signal that by calling the writer function one more time,
-with a @id{NULL} buffer (and size 0).
-
-The writer returns an error code:
-@N{0 means} no errors;
-any other value means an error and stops @Lid{lua_dump} from
-calling the writer again.
-
-}
-
-@APIEntry{void lua_xmove (lua_State *from, lua_State *to, int n);|
-@apii{?,?,-}
-
-Exchange values between different threads of the same state.
-
-This function pops @id{n} values from the stack @id{from},
-and pushes them onto the stack @id{to}.
-
-}
-
-@APIEntry{int lua_yield (lua_State *L, int nresults);|
-@apii{?,?,v}
-
-This function is equivalent to @Lid{lua_yieldk},
-but it has no continuation @see{continuations}.
-Therefore, when the thread resumes,
-it continues the function that called
-the function calling @id{lua_yield}.
-To avoid surprises,
-this function should be called only in a tail call.
-
-}
-
-
-@APIEntry{
-int lua_yieldk (lua_State *L,
- int nresults,
- lua_KContext ctx,
- lua_KFunction k);|
-@apii{?,?,v}
-
-Yields a coroutine (thread).
-
-When a @N{C function} calls @Lid{lua_yieldk},
-the running coroutine suspends its execution,
-and the call to @Lid{lua_resume} that started this coroutine returns.
-The parameter @id{nresults} is the number of values from the stack
-that will be passed as results to @Lid{lua_resume}.
-
-When the coroutine is resumed again,
-Lua calls the given @x{continuation function} @id{k} to continue
-the execution of the @N{C function} that yielded @see{continuations}.
-This continuation function receives the same stack
-from the previous function,
-with the @id{n} results removed and
-replaced by the arguments passed to @Lid{lua_resume}.
-Moreover,
-the continuation function receives the value @id{ctx}
-that was passed to @Lid{lua_yieldk}.
-
-Usually, this function does not return;
-when the coroutine eventually resumes,
-it continues executing the continuation function.
-However, there is one special case,
-which is when this function is called
-from inside a line or a count hook @see{debugI}.
-In that case, @id{lua_yieldk} should be called with no continuation
-(probably in the form of @Lid{lua_yield}) and no results,
-and the hook should return immediately after the call.
-Lua will yield and,
-when the coroutine resumes again,
-it will continue the normal execution
-of the (Lua) function that triggered the hook.
-
-This function can raise an error if it is called from a thread
-with a pending C call with no continuation function
-(what is called a @emphx{C-call boundary}),
-or it is called from a thread that is not running inside a resume
-(typically the main thread).
-
-}
-
-}
-
-@sect2{debugI| @title{The Debug Interface}
-
-Lua has no built-in debugging facilities.
-Instead, it offers a special interface
-by means of functions and @emph{hooks}.
-This interface allows the construction of different
-kinds of debuggers, profilers, and other tools
-that need @Q{inside information} from the interpreter.
-
-
-@APIEntry{
-typedef struct lua_Debug {
- int event;
- const char *name; /* (n) */
- const char *namewhat; /* (n) */
- const char *what; /* (S) */
- const char *source; /* (S) */
- size_t srclen; /* (S) */
- int currentline; /* (l) */
- int linedefined; /* (S) */
- int lastlinedefined; /* (S) */
- unsigned char nups; /* (u) number of upvalues */
- unsigned char nparams; /* (u) number of parameters */
- char isvararg; /* (u) */
- unsigned char extraargs; /* (t) number of extra arguments */
- char istailcall; /* (t) */
- int ftransfer; /* (r) index of first value transferred */
- int ntransfer; /* (r) number of transferred values */
- char short_src[LUA_IDSIZE]; /* (S) */
- /* private part */
- @rep{other fields}
-} lua_Debug;
-|
-
-A structure used to carry different pieces of
-information about a function or an activation record.
-@Lid{lua_getstack} fills only the private part
-of this structure, for later use.
-To fill the other fields of @Lid{lua_Debug} with useful information,
-you must call @Lid{lua_getinfo} with an appropriate parameter.
-(Specifically, to get a field,
-you must add the letter between parentheses in the field's comment
-to the parameter @id{what} of @Lid{lua_getinfo}.)
-
-The fields of @Lid{lua_Debug} have the following meaning:
-@description{
-
-@item{@id{source}|
-the source of the chunk that created the function.
-If @T{source} starts with a @Char{@At},
-it means that the function was defined in a file where
-the file name follows the @Char{@At}.
-If @T{source} starts with a @Char{=},
-the remainder of its contents describes the source in a user-dependent manner.
-Otherwise,
-the function was defined in a string where
-@T{source} is that string.
-}
-
-@item{@id{srclen}|
-The length of the string @id{source}.
-}
-
-@item{@id{short_src}|
-a @Q{printable} version of @T{source}, to be used in error messages.
-}
-
-@item{@id{linedefined}|
-the line number where the definition of the function starts.
-}
-
-@item{@id{lastlinedefined}|
-the line number where the definition of the function ends.
-}
-
-@item{@id{what}|
-the string @T{"Lua"} if the function is a Lua function,
-@T{"C"} if it is a @N{C function},
-@T{"main"} if it is the main part of a chunk.
-}
-
-@item{@id{currentline}|
-the current line where the given function is executing.
-When no line information is available,
-@T{currentline} is set to @num{-1}.
-}
-
-@item{@id{name}|
-a reasonable name for the given function.
-Because functions in Lua are first-class values,
-they do not have a fixed name:
-some functions can be the value of multiple global variables,
-while others can be stored only in a table field.
-The @T{lua_getinfo} function checks how the function was
-called to find a suitable name.
-If it cannot find a name,
-then @id{name} is set to @id{NULL}.
-}
-
-@item{@id{namewhat}|
-explains the @T{name} field.
-The value of @T{namewhat} can be
-@T{"global"}, @T{"local"}, @T{"upvalue"},
-@T{"field"}, @T{""} (the empty string), plus some other options,
-according to how the function was called.
-(Lua uses the empty string when no other option seems to apply.)
-}
-
-@item{@id{istailcall}|
-true if this function invocation was called by a tail call.
-In this case, the caller of this level is not in the stack.
-}
-
-@item{@id{extraargs}|
-The number of extra arguments added by the call
-to functions called through @idx{__call} metamethods.
-(Each @idx{__call} metavalue adds a single extra argument,
-the object being called,
-but there may be a chain of @idx{__call} metavalues.)
-}
-
-@item{@id{nups}|
-the number of upvalues of the function.
-}
-
-@item{@id{nparams}|
-the number of parameters of the function
-(always @N{0 for} @N{C functions}).
-}
-
-@item{@id{isvararg}|
-true if the function is a variadic function
-(always true for @N{C functions}).
-}
-
-@item{@id{ftransfer}|
-the index in the stack of the first value being @Q{transferred},
-that is, parameters in a call or return values in a return.
-(The other values are in consecutive indices.)
-Using this index, you can access and modify these values
-through @Lid{lua_getlocal} and @Lid{lua_setlocal}.
-This field is only meaningful during a
-call hook, denoting the first parameter,
-or a return hook, denoting the first value being returned.
-(For call hooks, this value is always 1.)
-}
-
-@item{@id{ntransfer}|
-The number of values being transferred (see previous item).
-(For calls of Lua functions,
-this value is always equal to @id{nparams}.)
-}
-
-}
-
-}
-
-@APIEntry{lua_Hook lua_gethook (lua_State *L);|
-@apii{0,0,-}
-
-Returns the current hook function.
-
-}
-
-@APIEntry{int lua_gethookcount (lua_State *L);|
-@apii{0,0,-}
-
-Returns the current hook count.
-
-}
-
-@APIEntry{int lua_gethookmask (lua_State *L);|
-@apii{0,0,-}
-
-Returns the current hook mask.
-
-}
-
-@APIEntry{int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar);|
-@apii{0|1,0|1|2,m}
-
-Gets information about a specific function or function invocation.
-
-To get information about a function invocation,
-the parameter @id{ar} must be a valid activation record that was
-filled by a previous call to @Lid{lua_getstack} or
-given as argument to a hook @seeC{lua_Hook}.
-
-To get information about a function, you push it onto the stack
-and start the @id{what} string with the character @Char{>}.
-(In that case,
-@id{lua_getinfo} pops the function from the top of the stack.)
-For instance, to know in which line a function @id{f} was defined,
-you can write the following code:
-@verbatim{
-lua_Debug ar;
-lua_getglobal(L, "f"); /* get global 'f' */
-lua_getinfo(L, ">S", &ar);
-printf("%d\n", ar.linedefined);
-}
-
-Each character in the string @id{what}
-selects some fields of the structure @id{ar} to be filled or
-a value to be pushed on the stack.
-(These characters are also documented in the declaration of
-the structure @Lid{lua_Debug},
-between parentheses in the comments following each field.)
-@description{
-
-@item{@Char{f}|
-pushes onto the stack the function that is
-running at the given level;
-}
-
-@item{@Char{l}| fills in the field @id{currentline};
-}
-
-@item{@Char{n}| fills in the fields @id{name} and @id{namewhat};
-}
-
-@item{@Char{r}| fills in the fields @id{ftransfer} and @id{ntransfer};
-}
-
-@item{@Char{S}|
-fills in the fields @id{source}, @id{short_src},
-@id{linedefined}, @id{lastlinedefined}, and @id{what};
-}
-
-@item{@Char{t}| fills in the fields @id{istailcall} and @id{extraargs};
-}
-
-@item{@Char{u}| fills in the fields
-@id{nups}, @id{nparams}, and @id{isvararg};
-}
-
-@item{@Char{L}|
-pushes onto the stack a table whose indices are
-the lines on the function with some associated code,
-that is, the lines where you can put a break point.
-(Lines with no code include empty lines and comments.)
-If this option is given together with option @Char{f},
-its table is pushed after the function.
-This is the only option that can raise a memory error.
-}
-
-}
-
-This function returns 0 to signal an invalid option in @id{what};
-even then the valid options are handled correctly.
-
-}
-
-@APIEntry{const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n);|
-@apii{0,0|1,-}
-
-Gets information about a local variable or a temporary value
-of a given activation record or a given function.
-
-In the first case,
-the parameter @id{ar} must be a valid activation record that was
-filled by a previous call to @Lid{lua_getstack} or
-given as argument to a hook @seeC{lua_Hook}.
-The index @id{n} selects which local variable to inspect;
-see @Lid{debug.getlocal} for details about variable indices
-and names.
-
-@Lid{lua_getlocal} pushes the variable's value onto the stack
-and returns its name.
-
-In the second case, @id{ar} must be @id{NULL} and the function
-to be inspected must be on the top of the stack.
-In this case, only parameters of Lua functions are visible
-(as there is no information about what variables are active)
-and no values are pushed onto the stack.
-
-Returns @id{NULL} (and pushes nothing)
-when the index is greater than
-the number of active local variables.
-
-}
-
-@APIEntry{int lua_getstack (lua_State *L, int level, lua_Debug *ar);|
-@apii{0,0,-}
-
-Gets information about the interpreter runtime stack.
-
-This function fills parts of a @Lid{lua_Debug} structure with
-an identification of the @emph{activation record}
-of the function executing at a given level.
-@N{Level 0} is the current running function,
-whereas level @M{n+1} is the function that has called level @M{n}
-(except for tail calls, which do not count in the stack).
-When called with a level greater than the stack depth,
-@Lid{lua_getstack} returns 0;
-otherwise it returns 1.
-
-}
-
-@APIEntry{const char *lua_getupvalue (lua_State *L, int funcindex, int n);|
-@apii{0,0|1,-}
-
-Gets information about the @id{n}-th upvalue
-of the closure at index @id{funcindex}.
-It pushes the upvalue's value onto the stack
-and returns its name.
-Returns @id{NULL} (and pushes nothing)
-when the index @id{n} is greater than the number of upvalues.
-
-See @Lid{debug.getupvalue} for more information about upvalues.
-
-}
-
-@APIEntry{typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);|
-
-Type for debugging hook functions.
-
-Whenever a hook is called, its @id{ar} argument has its field
-@id{event} set to the specific event that triggered the hook.
-Lua identifies these events with the following constants:
-@defid{LUA_HOOKCALL}, @defid{LUA_HOOKRET},
-@defid{LUA_HOOKTAILCALL}, @defid{LUA_HOOKLINE},
-and @defid{LUA_HOOKCOUNT}.
-Moreover, for line events, the field @id{currentline} is also set.
-To get the value of any other field in @id{ar},
-the hook must call @Lid{lua_getinfo}.
-
-For call events, @id{event} can be @id{LUA_HOOKCALL},
-the normal value, or @id{LUA_HOOKTAILCALL}, for a tail call;
-in this case, there will be no corresponding return event.
-
-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,
-this execution occurs without any calls to hooks.
-
-Hook functions cannot have continuations,
-that is, they cannot call @Lid{lua_yieldk},
-@Lid{lua_pcallk}, or @Lid{lua_callk} with a non-null @id{k}.
-
-Hook functions can yield under the following conditions:
-Only count and line events can yield;
-to yield, a hook function must finish its execution
-calling @Lid{lua_yield} with @id{nresults} equal to zero
-(that is, with no values).
-
-}
-
-@APIEntry{void lua_sethook (lua_State *L, lua_Hook f, int mask, int count);|
-@apii{0,0,-}
-
-Sets the debugging hook function.
-
-Argument @id{f} is the hook function.
-@id{mask} specifies on which events the hook will be called:
-it is formed by a bitwise OR of the constants
-@defid{LUA_MASKCALL},
-@defid{LUA_MASKRET},
-@defid{LUA_MASKLINE},
-and @defid{LUA_MASKCOUNT}.
-The @id{count} argument is only meaningful when the mask
-includes @id{LUA_MASKCOUNT}.
-For each event, the hook is called as explained below:
-@description{
-
-@item{The call hook| is called when the interpreter calls a function.
-The hook is called just after Lua enters the new function.
-}
-
-@item{The return hook| is called when the interpreter returns from a function.
-The hook is called just before Lua leaves the function.
-}
-
-@item{The line hook| 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.
-}
-
-@item{The count hook| is called after the interpreter executes every
-@T{count} instructions.
-This event only happens while Lua is executing a Lua function.
-}
-
-}
-
-Hooks are disabled by setting @id{mask} to zero.
-
-}
-
-@APIEntry{const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n);|
-@apii{0|1,0,-}
-
-Sets the value of a local variable of a given activation record.
-It assigns the value on the top of the stack
-to the variable and returns its name.
-It also pops the value from the stack.
-
-Returns @id{NULL} (and pops nothing)
-when the index is greater than
-the number of active local variables.
-
-Parameters @id{ar} and @id{n} are as in the function @Lid{lua_getlocal}.
-
-}
-
-@APIEntry{const char *lua_setupvalue (lua_State *L, int funcindex, int n);|
-@apii{0|1,0,-}
-
-Sets the value of a closure's upvalue.
-It assigns the value on the top of the stack
-to the upvalue and returns its name.
-It also pops the value from the stack.
-
-Returns @id{NULL} (and pops nothing)
-when the index @id{n} is greater than the number of upvalues.
-
-Parameters @id{funcindex} and @id{n} are as in
-the function @Lid{lua_getupvalue}.
-
-}
-
-@APIEntry{void *lua_upvalueid (lua_State *L, int funcindex, int n);|
-@apii{0,0,-}
-
-Returns a unique identifier for the upvalue numbered @id{n}
-from the closure at index @id{funcindex}.
-
-These unique identifiers allow a program to check whether different
-closures share upvalues.
-Lua closures that share an upvalue
-(that is, that access a same external local variable)
-will return identical ids for those upvalue indices.
-
-Parameters @id{funcindex} and @id{n} are as in
-the function @Lid{lua_getupvalue},
-but @id{n} cannot be greater than the number of upvalues.
-
-}
-
-@APIEntry{
-void lua_upvaluejoin (lua_State *L, int funcindex1, int n1,
- int funcindex2, int n2);|
-@apii{0,0,-}
-
-Make the @id{n1}-th upvalue of the Lua closure at index @id{funcindex1}
-refer to the @id{n2}-th upvalue of the Lua closure at index @id{funcindex2}.
-
-}
-
-}
-
-}
-
-
-@C{-------------------------------------------------------------------------}
-@sect1{auxlib|@title{The Auxiliary Library}
-
-@simplesect{
-
-@index{lauxlib.h}
-The @def{auxiliary library} 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.
-
-All functions and types from the auxiliary library
-are defined in the header file @id{lauxlib.h} and
-have a prefix @id{luaL_}.
-
-All functions in the auxiliary library are built on
-top of the basic API,
-and so they provide nothing that cannot be done with that API.
-Nevertheless, the use of the auxiliary library ensures
-more consistency to your code.
-
-
-Several functions in the auxiliary library use internally some
-extra stack slots.
-When a function in the auxiliary library uses less than five slots,
-it does not check the stack size;
-it simply assumes that there are enough slots.
-
-Several functions in the auxiliary library are used to
-check @N{C function} arguments.
-Because the error message is formatted for arguments
-(e.g., @St{bad argument #1}),
-you should not use these functions for other stack values.
-
-Functions called @id{luaL_check*}
-always raise an error if the check is not satisfied.
-
-}
-
-
-@sect2{@title{Functions and Types}
-
-Here we list all functions and types from the auxiliary library
-in alphabetical order.
-
-
-@APIEntry{void luaL_addchar (luaL_Buffer *B, char c);|
-@apii{?,?,m}
-
-Adds the byte @id{c} to the buffer @id{B}
-@seeC{luaL_Buffer}.
-
-}
-
-@APIEntry{
-const void luaL_addgsub (luaL_Buffer *B, const char *s,
- const char *p, const char *r);|
-@apii{?,?,m}
-
-Adds a copy of the string @id{s} to the buffer @id{B} @seeC{luaL_Buffer},
-replacing any occurrence of the string @id{p}
-with the string @id{r}.
-
-}
-
-@APIEntry{void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l);|
-@apii{?,?,m}
-
-Adds the string pointed to by @id{s} with length @id{l} to
-the buffer @id{B}
-@seeC{luaL_Buffer}.
-The string can contain @x{embedded zeros}.
-
-}
-
-@APIEntry{void luaL_addsize (luaL_Buffer *B, size_t n);|
-@apii{?,?,-}
-
-Adds to the buffer @id{B}
-a string of length @id{n} previously copied to the
-buffer area @seeC{luaL_prepbuffer}.
-
-}
-
-@APIEntry{void luaL_addstring (luaL_Buffer *B, const char *s);|
-@apii{?,?,m}
-
-Adds the zero-terminated string pointed to by @id{s}
-to the buffer @id{B}
-@seeC{luaL_Buffer}.
-
-}
-
-@APIEntry{void luaL_addvalue (luaL_Buffer *B);|
-@apii{?,?,m}
-
-Adds the value on the top of the stack
-to the buffer @id{B}
-@seeC{luaL_Buffer}.
-Pops the value.
-
-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.
-
-}
-
-@APIEntry{
-void luaL_argcheck (lua_State *L,
- int cond,
- int arg,
- const char *extramsg);|
-@apii{0,0,v}
-
-Checks whether @id{cond} is true.
-If it is not, raises an error with a standard message @seeF{luaL_argerror}.
-
-}
-
-@APIEntry{int luaL_argerror (lua_State *L, int arg, const char *extramsg);|
-@apii{0,0,v}
-
-Raises an error reporting a problem with argument @id{arg}
-of the @N{C function} that called it,
-using a standard message
-that includes @id{extramsg} as a comment:
-@verbatim{
-bad argument #@rep{arg} to '@rep{funcname}' (@rep{extramsg})
-}
-This function never returns.
-
-}
-
-@APIEntry{
-void luaL_argexpected (lua_State *L,
- int cond,
- int arg,
- const char *tname);|
-@apii{0,0,v}
-
-Checks whether @id{cond} is true.
-If it is not, raises an error about the type of the argument @id{arg}
-with a standard message @seeF{luaL_typeerror}.
-
-}
-
-@APIEntry{typedef struct luaL_Buffer luaL_Buffer;|
-
-Type for a @def{string buffer}.
-
-A string buffer allows @N{C code} to build Lua strings piecemeal.
-Its pattern of use is as follows:
-@itemize{
-
-@item{First declare a variable @id{b} of type @Lid{luaL_Buffer}.}
-
-@item{Then initialize it with a call @T{luaL_buffinit(L,&b)}.}
-
-@item{
-Then add string pieces to the buffer calling any of
-the @id{luaL_add*} functions.
-}
-
-@item{
-Finish by calling @T{luaL_pushresult(&b)}.
-This call leaves the final string on the top of the stack.
-}
-
-}
-
-If you know beforehand the maximum size of the resulting string,
-you can use the buffer like this:
-@itemize{
-
-@item{First declare a variable @id{b} of type @Lid{luaL_Buffer}.}
-
-@item{Then initialize it and preallocate a space of
-size @id{sz} with a call @T{luaL_buffinitsize(L,&b,sz)}.}
-
-@item{Then produce the string into that space.}
-
-@item{
-Finish by calling @T{luaL_pushresultsize(&b,sz)},
-where @id{sz} is the total size of the resulting string
-copied into that space (which may be less than or
-equal to the preallocated size).
-}
-
-}
-
-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
-the top of the stack is.
-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 @Lid{luaL_addvalue}.)
-After calling @Lid{luaL_pushresult},
-the stack is back to its level when the buffer was initialized,
-plus the final string on its top.
-
-}
-
-@APIEntry{char *luaL_buffaddr (luaL_Buffer *B);|
-@apii{0,0,-}
-
-Returns the address of the current content of buffer @id{B}
-@seeC{luaL_Buffer}.
-Note that any addition to the buffer may invalidate this address.
-
-}
-
-@APIEntry{void luaL_buffinit (lua_State *L, luaL_Buffer *B);|
-@apii{0,?,-}
-
-Initializes a buffer @id{B}
-@seeC{luaL_Buffer}.
-This function does not allocate any space;
-the buffer must be declared as a variable.
-
-}
-
-@APIEntry{size_t luaL_bufflen (luaL_Buffer *B);|
-@apii{0,0,-}
-
-Returns the length of the current content of buffer @id{B}
-@seeC{luaL_Buffer}.
-
-}
-
-@APIEntry{char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz);|
-@apii{?,?,m}
-
-Equivalent to the sequence
-@Lid{luaL_buffinit}, @Lid{luaL_prepbuffsize}.
-
-}
-
-@APIEntry{void luaL_buffsub (luaL_Buffer *B, int n);|
-@apii{?,?,-}
-
-Removes @id{n} bytes from the buffer @id{B}
-@seeC{luaL_Buffer}.
-The buffer must have at least that many bytes.
-
-}
-
-@APIEntry{int luaL_callmeta (lua_State *L, int obj, const char *e);|
-@apii{0,0|1,e}
-
-Calls a metamethod.
-
-If the object at index @id{obj} has a metatable and this
-metatable has a field @id{e},
-this function calls this field passing the object as its only argument.
-In this case this function returns true and pushes onto the
-stack the value returned by the call.
-If there is no metatable or no metamethod,
-this function returns false without pushing any value on the stack.
-
-}
-
-@APIEntry{void luaL_checkany (lua_State *L, int arg);|
-@apii{0,0,v}
-
-Checks whether the function has an argument
-of any type (including @nil) at position @id{arg}.
-
-}
-
-@APIEntry{lua_Integer luaL_checkinteger (lua_State *L, int arg);|
-@apii{0,0,v}
-
-Checks whether the function argument @id{arg} is an integer
-(or can be converted to an integer)
-and returns this integer.
-
-}
-
-@APIEntry{const char *luaL_checklstring (lua_State *L, int arg, size_t *l);|
-@apii{0,0,v}
-
-Checks whether the function argument @id{arg} is a string
-and returns this string;
-if @id{l} is not @id{NULL} fills its referent
-with the string's length.
-
-This function uses @Lid{lua_tolstring} to get its result,
-so all conversions and caveats of that function apply here.
-
-}
-
-@APIEntry{lua_Number luaL_checknumber (lua_State *L, int arg);|
-@apii{0,0,v}
-
-Checks whether the function argument @id{arg} is a number
-and returns this number converted to a @id{lua_Number}.
-
-}
-
-@APIEntry{
-int luaL_checkoption (lua_State *L,
- int arg,
- const char *def,
- const char *const lst[]);|
-@apii{0,0,v}
-
-Checks whether the function argument @id{arg} is a string and
-searches for this string in the array @id{lst}
-(which must be NULL-terminated).
-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.
-
-If @id{def} is not @id{NULL},
-the function uses @id{def} as a default value when
-there is no argument @id{arg} or when this argument is @nil.
-
-This is a useful function for mapping strings to @N{C enums}.
-(The usual convention in Lua libraries is
-to use strings instead of numbers to select options.)
-
-}
-
-@APIEntry{void luaL_checkstack (lua_State *L, int sz, const char *msg);|
-@apii{0,0,v}
-
-Grows the stack size to @T{top + sz} elements,
-raising an error if the stack cannot grow to that size.
-@id{msg} is an additional text to go into the error message
-(or @id{NULL} for no additional text).
-
-}
-
-@APIEntry{const char *luaL_checkstring (lua_State *L, int arg);|
-@apii{0,0,v}
-
-Checks whether the function argument @id{arg} is a string
-and returns this string.
-
-This function uses @Lid{lua_tolstring} to get its result,
-so all conversions and caveats of that function apply here.
-
-}
-
-@APIEntry{void luaL_checktype (lua_State *L, int arg, int t);|
-@apii{0,0,v}
-
-Checks whether the function argument @id{arg} has type @id{t}.
-See @Lid{lua_type} for the encoding of types for @id{t}.
-
-}
-
-@APIEntry{void *luaL_checkudata (lua_State *L, int arg, const char *tname);|
-@apii{0,0,v}
-
-Checks whether the function argument @id{arg} is a userdata
-of the type @id{tname} @seeC{luaL_newmetatable} and
-returns the userdata's memory-block address @seeC{lua_touserdata}.
-
-}
-
-@APIEntry{void luaL_checkversion (lua_State *L);|
-@apii{0,0,v}
-
-Checks whether the code making the call and the Lua library being called
-are using the same version of Lua and the same numeric types.
-
-}
-
-@APIEntry{int luaL_dofile (lua_State *L, const char *filename);|
-@apii{0,?,m}
-
-Loads and runs the given file.
-It is defined as the following macro:
-@verbatim{
-(luaL_loadfile(L, filename) || lua_pcall(L, 0, LUA_MULTRET, 0))
-}
-It @N{returns 0} (@Lid{LUA_OK}) if there are no errors,
-or 1 in case of errors.
-(Except for out-of-memory errors, which are raised.)
-
-}
-
-@APIEntry{int luaL_dostring (lua_State *L, const char *str);|
-@apii{0,?,-}
-
-Loads and runs the given string.
-It is defined as the following macro:
-@verbatim{
-(luaL_loadstring(L, str) || lua_pcall(L, 0, LUA_MULTRET, 0))
-}
-It @N{returns 0} (@Lid{LUA_OK}) if there are no errors,
-or 1 in case of errors.
-
-}
-
-@APIEntry{int luaL_error (lua_State *L, const char *fmt, ...);|
-@apii{0,0,v}
-
-Raises an error.
-The error message format is given by @id{fmt}
-plus any extra arguments,
-following the same rules of @Lid{lua_pushfstring}.
-It also adds at the beginning of the message the file name and
-the line number where the error occurred,
-if this information is available.
-
-This function never returns,
-but it is an idiom to use it in @N{C functions}
-as @T{return luaL_error(@rep{args})}.
-
-}
-
-@APIEntry{int luaL_execresult (lua_State *L, int stat);|
-@apii{0,3,m}
-
-This function produces the return values for
-process-related functions in the standard library
-(@Lid{os.execute} and @Lid{io.close}).
-
-}
-
-@APIEntry{
-int luaL_fileresult (lua_State *L, int stat, const char *fname);|
-@apii{0,1|3,m}
-
-This function produces the return values for
-file-related functions in the standard library
-(@Lid{io.open}, @Lid{os.rename}, @Lid{file:seek}, etc.).
-
-}
-
-@APIEntry{int luaL_getmetafield (lua_State *L, int obj, const char *e);|
-@apii{0,0|1,m}
-
-Pushes onto the stack the field @id{e} from the metatable
-of the object at index @id{obj} and returns the type of the pushed value.
-If the object does not have a metatable,
-or if the metatable does not have this field,
-pushes nothing and returns @id{LUA_TNIL}.
-
-}
-
-@APIEntry{int luaL_getmetatable (lua_State *L, const char *tname);|
-@apii{0,1,m}
-
-Pushes onto the stack the metatable associated with the name @id{tname}
-in the registry @seeC{luaL_newmetatable},
-or @nil if there is no metatable associated with that name.
-Returns the type of the pushed value.
-
-}
-
-@APIEntry{int luaL_getsubtable (lua_State *L, int idx, const char *fname);|
-@apii{0,1,e}
-
-Ensures that the value @T{t[fname]},
-where @id{t} is the value at index @id{idx},
-is a table,
-and pushes that table onto the stack.
-Returns true if it finds a previous table there
-and false if it creates a new table.
-
-}
-
-@APIEntry{
-const char *luaL_gsub (lua_State *L,
- const char *s,
- const char *p,
- const char *r);|
-@apii{0,1,m}
-
-Creates a copy of string @id{s},
-replacing any occurrence of the string @id{p}
-with the string @id{r}.
-Pushes the resulting string on the stack and returns it.
-
-}
-
-@APIEntry{lua_Integer luaL_len (lua_State *L, int index);|
-@apii{0,0,e}
-
-Returns the @Q{length} of the value at the given index
-as a number;
-it is equivalent to the @Char{#} operator in Lua @see{len-op}.
-Raises an error if the result of the operation is not an integer.
-(This case can only happen through metamethods.)
-
-}
-
-@APIEntry{
-int luaL_loadbuffer (lua_State *L,
- const char *buff,
- size_t sz,
- const char *name);|
-@apii{0,1,-}
-
-Equivalent to @Lid{luaL_loadbufferx} with @id{mode} equal to @id{NULL}.
-
-}
-
-
-@APIEntry{
-int luaL_loadbufferx (lua_State *L,
- const char *buff,
- size_t sz,
- const char *name,
- const char *mode);|
-@apii{0,1,-}
-
-Loads a buffer as a Lua chunk.
-This function uses @Lid{lua_load} to load the chunk in the
-buffer pointed to by @id{buff} with size @id{sz}.
-
-This function returns the same results as @Lid{lua_load}.
-@id{name} is the chunk name,
-used for debug information and error messages.
-The string @id{mode} works as in the function @Lid{lua_load}.
-In particular, this function supports mode @Char{B} for
-fixed buffers.
-
-}
-
-
-@APIEntry{int luaL_loadfile (lua_State *L, const char *filename);|
-@apii{0,1,m}
-
-Equivalent to @Lid{luaL_loadfilex} with @id{mode} equal to @id{NULL}.
-
-}
-
-@APIEntry{int luaL_loadfilex (lua_State *L, const char *filename,
- const char *mode);|
-@apii{0,1,m}
-
-Loads a file as a Lua chunk.
-This function uses @Lid{lua_load} to load the chunk in the file
-named @id{filename}.
-If @id{filename} is @id{NULL},
-then it loads from the standard input.
-The first line in the file is ignored if it starts with a @T{#}.
-
-The string @id{mode} works as in the function @Lid{lua_load}.
-
-This function returns the same results as @Lid{lua_load},
-or @Lid{LUA_ERRFILE} for file-related errors.
-
-As @Lid{lua_load}, this function only loads the chunk;
-it does not run it.
-
-}
-
-@APIEntry{int luaL_loadstring (lua_State *L, const char *s);|
-@apii{0,1,-}
-
-Loads a string as a Lua chunk.
-This function uses @Lid{lua_load} to load the chunk in
-the zero-terminated string @id{s}.
-
-This function returns the same results as @Lid{lua_load}.
-
-Also as @Lid{lua_load}, this function only loads the chunk;
-it does not run it.
-
-}
-
-@APIEntry{unsigned int luaL_makeseed (lua_State *L);|
-@apii{0,0,-}
-
-Returns a value with a weak attempt for randomness.
-The parameter @id{L} can be @id{NULL}
-if there is no Lua state available.
-
-}
-
-
-@APIEntry{void luaL_newlib (lua_State *L, const luaL_Reg l[]);|
-@apii{0,1,m}
-
-Creates a new table and registers there
-the functions in the list @id{l}.
-
-It is implemented as the following macro:
-@verbatim{
-(luaL_newlibtable(L,l), luaL_setfuncs(L,l,0))
-}
-The array @id{l} must be the actual array,
-not a pointer to it.
-
-}
-
-@APIEntry{void luaL_newlibtable (lua_State *L, const luaL_Reg l[]);|
-@apii{0,1,m}
-
-Creates a new table with a size optimized
-to store all entries in the array @id{l}
-(but does not actually store them).
-It is intended to be used in conjunction with @Lid{luaL_setfuncs}
-@seeF{luaL_newlib}.
-
-It is implemented as a macro.
-The array @id{l} must be the actual array,
-not a pointer to it.
-
-}
-
-@APIEntry{int luaL_newmetatable (lua_State *L, const char *tname);|
-@apii{0,1,m}
-
-If the registry already has the key @id{tname},
-returns 0.
-Otherwise,
-creates a new table to be used as a metatable for userdata,
-adds to this new table the pair @T{__name = tname},
-adds to the registry the pair @T{[tname] = new table},
-and returns 1.
-
-In both cases,
-the function pushes onto the stack the final value associated
-with @id{tname} in the registry.
-
-}
-
-@APIEntry{lua_State *luaL_newstate (void);|
-@apii{0,0,-}
-
-Creates a new Lua state.
-It calls @Lid{lua_newstate} with @Lid{luaL_alloc} as
-the allocator function and the result of @T{luaL_makeseed(NULL)}
-as the seed,
-and then sets a warning function and a panic function @see{C-error}
-that print messages to the standard error output.
-
-Returns the new state,
-or @id{NULL} if there is a @x{memory allocation error}.
-
-}
-
-@APIEntry{
-T luaL_opt (L, func, arg, dflt);|
-@apii{0,0,-}
-
-This macro is defined as follows:
-@verbatim{
-(lua_isnoneornil(L,(arg)) ? (dflt) : func(L,(arg)))
-}
-In words, if the argument @id{arg} is nil or absent,
-the macro results in the default @id{dflt}.
-Otherwise, it results in the result of calling @id{func}
-with the state @id{L} and the argument index @id{arg} as
-arguments.
-Note that it evaluates the expression @id{dflt} only if needed.
-
-}
-
-@APIEntry{
-lua_Integer luaL_optinteger (lua_State *L,
- int arg,
- lua_Integer d);|
-@apii{0,0,v}
-
-If the function argument @id{arg} is an integer
-(or it is convertible to an integer),
-returns this integer.
-If this argument is absent or is @nil,
-returns @id{d}.
-Otherwise, raises an error.
-
-}
-
-@APIEntry{
-const char *luaL_optlstring (lua_State *L,
- int arg,
- const char *d,
- size_t *l);|
-@apii{0,0,v}
-
-If the function argument @id{arg} is a string,
-returns this string.
-If this argument is absent or is @nil,
-returns @id{d}.
-Otherwise, raises an error.
-
-If @id{l} is not @id{NULL},
-fills its referent with the result's length.
-If the result is @id{NULL}
-(only possible when returning @id{d} and @T{d == NULL}),
-its length is considered zero.
-
-This function uses @Lid{lua_tolstring} to get its result,
-so all conversions and caveats of that function apply here.
-
-}
-
-@APIEntry{lua_Number luaL_optnumber (lua_State *L, int arg, lua_Number d);|
-@apii{0,0,v}
-
-If the function argument @id{arg} is a number,
-returns this number as a @id{lua_Number}.
-If this argument is absent or is @nil,
-returns @id{d}.
-Otherwise, raises an error.
-
-}
-
-@APIEntry{
-const char *luaL_optstring (lua_State *L,
- int arg,
- const char *d);|
-@apii{0,0,v}
-
-If the function argument @id{arg} is a string,
-returns this string.
-If this argument is absent or is @nil,
-returns @id{d}.
-Otherwise, raises an error.
-
-}
-
-@APIEntry{char *luaL_prepbuffer (luaL_Buffer *B);|
-@apii{?,?,m}
-
-Equivalent to @Lid{luaL_prepbuffsize}
-with the predefined size @defid{LUAL_BUFFERSIZE}.
-
-}
-
-@APIEntry{char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz);|
-@apii{?,?,m}
-
-Returns an address to a space of size @id{sz}
-where you can copy a string to be added to buffer @id{B}
-@seeC{luaL_Buffer}.
-After copying the string into this space you must call
-@Lid{luaL_addsize} with the size of the string to actually add
-it to the buffer.
-
-}
-
-@APIEntry{void luaL_pushfail (lua_State *L);|
-@apii{0,1,-}
-
-Pushes the @fail value onto the stack @see{libraries}.
-
-}
-
-@APIEntry{void luaL_pushresult (luaL_Buffer *B);|
-@apii{?,1,m}
-
-Finishes the use of buffer @id{B} leaving the final string on
-the top of the stack.
-
-}
-
-@APIEntry{void luaL_pushresultsize (luaL_Buffer *B, size_t sz);|
-@apii{?,1,m}
-
-Equivalent to the sequence @Lid{luaL_addsize}, @Lid{luaL_pushresult}.
-
-}
-
-@APIEntry{int luaL_ref (lua_State *L, int t);|
-@apii{1,0,m}
-
-Creates and returns a @def{reference},
-in the table at index @id{t},
-for the object on the top of the stack (and pops the object).
-
-The reference system uses the integer keys of the table.
-A reference is a unique integer key;
-@Lid{luaL_ref} ensures the uniqueness of the keys it returns.
-The entry 1 is reserved for internal use.
-Before the first use of @Lid{luaL_ref},
-the integer keys of the table
-should form a proper sequence (no holes),
-and the value at entry 1 should be false:
-@nil if the sequence is empty,
-@false otherwise.
-You should not manually set integer keys in the table
-after the first use of @Lid{luaL_ref}.
-
-You can retrieve an object referred by the reference @id{r}
-by calling @T{lua_rawgeti(L,t,r)} or @T{lua_geti(L,t,r)}.
-The function @Lid{luaL_unref} frees a reference.
-
-If the object on the top of the stack is @nil,
-@Lid{luaL_ref} returns the constant @defid{LUA_REFNIL}.
-The constant @defid{LUA_NOREF} is guaranteed to be different
-from any reference returned by @Lid{luaL_ref}.
-
-}
-
-@APIEntry{
-typedef struct luaL_Reg {
- const char *name;
- lua_CFunction func;
-} luaL_Reg;
-|
-
-Type for arrays of functions to be registered by
-@Lid{luaL_setfuncs}.
-@id{name} is the function name and @id{func} is a pointer to
-the function.
-Any array of @Lid{luaL_Reg} must end with a sentinel entry
-in which both @id{name} and @id{func} are @id{NULL}.
-
-}
-
-@APIEntry{
-void luaL_requiref (lua_State *L, const char *modname,
- lua_CFunction openf, int glb);|
-@apii{0,1,e}
-
-If @T{package.loaded[modname]} is not true,
-calls the function @id{openf} with the string @id{modname} as an argument
-and sets the call result to @T{package.loaded[modname]},
-as if that function has been called through @Lid{require}.
-
-If @id{glb} is true,
-also stores the module into the global variable @id{modname}.
-
-Leaves a copy of the module on the stack.
-
-}
-
-@APIEntry{void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup);|
-@apii{nup,0,m}
-
-Registers all functions in the array @id{l}
-@seeC{luaL_Reg} into the table on the top of the stack
-(below optional upvalues, see next).
-
-When @id{nup} is not zero,
-all functions are created with @id{nup} upvalues,
-initialized with copies of the @id{nup} values
-previously pushed on the stack
-on top of the library table.
-These values are popped from the stack after the registration.
-
-A function with a @id{NULL} value represents a placeholder,
-which is filled with @false.
-
-}
-
-@APIEntry{void luaL_setmetatable (lua_State *L, const char *tname);|
-@apii{0,0,-}
-
-Sets the metatable of the object on the top of the stack
-as the metatable associated with name @id{tname}
-in the registry @seeC{luaL_newmetatable}.
-
-}
-
-@APIEntry{
-void *luaL_alloc (void *ud, void *ptr, size_t osize, size_t nsize);|
-
-A standard allocator function for Lua @seeF{lua_Alloc},
-built on top of the C functions @id{realloc} and @id{free}.
-
-}
-
-
-@APIEntry{
-typedef struct luaL_Stream {
- FILE *f;
- lua_CFunction closef;
-} luaL_Stream;
-|
-
-The standard representation for @x{file handles}
-used by the standard I/O library.
-
-A file handle is implemented as a full userdata,
-with a metatable called @id{LUA_FILEHANDLE}
-(where @id{LUA_FILEHANDLE} is a macro with the actual metatable's name).
-The metatable is created by the I/O library
-@seeF{luaL_newmetatable}.
-
-This userdata must start with the structure @id{luaL_Stream};
-it can contain other data after this initial structure.
-The field @id{f} points to the corresponding C stream,
-or it is @id{NULL} to indicate an incompletely created handle.
-The field @id{closef} points to a Lua function
-that will be called to close the stream
-when the handle is closed or collected;
-this function receives the file handle as its sole argument and
-must return either a true value, in case of success,
-or a false value plus an error message, in case of error.
-Once Lua calls this field,
-it changes the field value to @id{NULL}
-to signal that the handle is closed.
-
-}
-
-@APIEntry{void *luaL_testudata (lua_State *L, int arg, const char *tname);|
-@apii{0,0,m}
-
-This function works like @Lid{luaL_checkudata},
-except that, when the test fails,
-it returns @id{NULL} instead of raising an error.
-
-}
-
-@APIEntry{const char *luaL_tolstring (lua_State *L, int idx, size_t *len);|
-@apii{0,1,e}
-
-Converts any Lua value at the given index to a @N{C string}
-in a reasonable format.
-The resulting string is pushed onto the stack and also
-returned by the function @see{constchar}.
-If @id{len} is not @id{NULL},
-the function also sets @T{*len} with the string length.
-
-If the value has a metatable with a @idx{__tostring} field,
-then @id{luaL_tolstring} calls the corresponding metamethod
-with the value as argument,
-and uses the result of the call as its result.
-
-}
-
-@APIEntry{
-void luaL_traceback (lua_State *L, lua_State *L1, const char *msg,
- int level);|
-@apii{0,1,m}
-
-Creates and pushes a traceback of the stack @id{L1}.
-If @id{msg} is not @id{NULL}, it is appended
-at the beginning of the traceback.
-The @id{level} parameter tells at which level
-to start the traceback.
-
-}
-
-@APIEntry{int luaL_typeerror (lua_State *L, int arg, const char *tname);|
-@apii{0,0,v}
-
-Raises a type error for the argument @id{arg}
-of the @N{C function} that called it,
-using a standard message;
-@id{tname} is a @Q{name} for the expected type.
-This function never returns.
-
-}
-
-@APIEntry{const char *luaL_typename (lua_State *L, int index);|
-@apii{0,0,-}
-
-Returns the name of the type of the value at the given index.
-
-}
-
-@APIEntry{void luaL_unref (lua_State *L, int t, int ref);|
-@apii{0,0,-}
-
-Releases a reference @see{luaL_ref}.
-The integer @id{ref} must be either
-@Lid{LUA_NOREF}, @Lid{LUA_REFNIL},
-or a reference previously returned by @Lid{luaL_ref}
-and not already released.
-If @id{ref} is either @Lid{LUA_NOREF} or @Lid{LUA_REFNIL}
-this function does nothing.
-Otherwise, the entry is removed from the table,
-so that the referred object can be collected and
-the reference @id{ref} can be used again by @Lid{luaL_ref}.
-
-}
-
-@APIEntry{void luaL_where (lua_State *L, int lvl);|
-@apii{0,1,m}
-
-Pushes onto the stack a string identifying the current position
-of the control at level @id{lvl} in the call stack.
-Typically this string has the following format:
-@verbatim{
-@rep{chunkname}:@rep{currentline}:
-}
-@N{Level 0} is the running function,
-@N{level 1} is the function that called the running function,
-etc.
-
-This function is used to build a prefix for error messages.
-
-}
-
-}
-
-}
-
-
-@C{-------------------------------------------------------------------------}
-@sect1{libraries| @title{The Standard Libraries}
-
-@simplesect{
-
-The standard Lua libraries provide useful functions
-that are implemented @N{in C} through the @N{C API}.
-Some of these functions provide essential services to the language
-(e.g., @Lid{type} and @Lid{getmetatable});
-others provide access to outside services (e.g., I/O);
-and others could be implemented in Lua itself,
-but that for different reasons
-deserve an implementation in C (e.g., @Lid{table.sort}).
-
-All libraries are implemented through the official @N{C API}
-and are provided as separate @N{C modules}.
-Unless otherwise noted,
-these library functions do not adjust its number of arguments
-to its expected parameters.
-For instance, a function documented as @T{foo(arg)}
-should not be called without an argument.
-
-The notation @fail means a false value representing
-some kind of failure.
-(Currently, @fail is equal to @nil,
-but that may change in future versions.
-The recommendation is to always test the success of these functions
-with @T{(not status)}, instead of @T{(status == nil)}.)
-
-
-Currently, Lua has the following standard libraries:
-@itemize{
-
-@item{@link{predefined|basic library};}
-
-@item{@link{corolib|coroutine library};}
-
-@item{@link{packlib|package library};}
-
-@item{@link{strlib|string manipulation};}
-
-@item{@link{utf8|basic UTF-8 support};}
-
-@item{@link{tablib|table manipulation};}
-
-@item{@link{mathlib|mathematical functions} (sin, log, etc.);}
-
-@item{@link{iolib|input and output};}
-
-@item{@link{oslib|operating system facilities};}
-
-@item{@link{debuglib|debug facilities}.}
-
-}
-Except for the basic and the package libraries,
-each library provides all its functions as fields of a global table
-or as methods of its objects.
-
-}
-
-
-@sect2{lualib-h| @title{Loading the Libraries in C code}
-
-A @N{C host} program must explicitly load
-the standard libraries into a state,
-if it wants its scripts to use them.
-For that,
-the host program can call the function @Lid{luaL_openlibs}.
-Alternatively,
-the host can select which libraries to open,
-by using @Lid{luaL_openselectedlibs}.
-Both functions are declared in the header file @id{lualib.h}.
-@index{lualib.h}
-
-The stand-alone interpreter @id{lua} @see{lua-sa}
-already opens all standard libraries.
-
-@APIEntry{void luaL_openlibs (lua_State *L);|
-@apii{0,0,e}
-
-Opens all standard Lua libraries into the given state.
-
-}
-
-@APIEntry{void luaL_openselectedlibs (lua_State *L, int load, int preload);|
-@apii{0,0,e}
-
-Opens (loads) and preloads selected standard libraries into the state @id{L}.
-(To @emph{preload} means to add
-the library loader into the table @Lid{package.preload},
-so that the library can be required later by the program.
-Keep in mind that @Lid{require} itself is provided
-by the @emph{package} library.
-If a program does not load that library,
-it will be unable to require anything.)
-
-The integer @id{load} selects which libraries to load;
-the integer @id{preload} selects which to preload, among those not loaded.
-Both are masks formed by a bitwise OR of the following constants:
-@description{
-@item{@defid{LUA_GLIBK} | the basic library.}
-@item{@defid{LUA_LOADLIBK} | the package library.}
-@item{@defid{LUA_COLIBK} | the coroutine library.}
-@item{@defid{LUA_STRLIBK} | the string library.}
-@item{@defid{LUA_UTF8LIBK} | the UTF-8 library.}
-@item{@defid{LUA_TABLIBK} | the table library.}
-@item{@defid{LUA_MATHLIBK} | the mathematical library.}
-@item{@defid{LUA_IOLIBK} | the I/O library.}
-@item{@defid{LUA_OSLIBK} | the operating system library.}
-@item{@defid{LUA_DBLIBK} | the debug library.}
-}
-
-}
-
-}
-
-
-@sect2{predefined| @title{Basic Functions}
-
-The basic library provides core functions to Lua.
-If you do not include this library in your application,
-you should check carefully whether you need to provide
-implementations for some of its facilities.
-
-
-@LibEntry{assert (v [, message])|
-
-Raises an error if
-the value of its argument @id{v} is false (i.e., @nil or @false);
-otherwise, returns all its arguments.
-In case of error,
-@id{message} is the error object;
-when absent, it defaults to @St{assertion failed!}
-
-}
-
-@LibEntry{collectgarbage ([opt [, arg]])|
-
-This function is a generic interface to the garbage collector.
-It performs different functions according to its first argument, @id{opt}:
-@description{
-
-@item{@St{collect}|
-Performs a full garbage-collection cycle.
-This is the default option.
-}
-
-@item{@St{stop}|
-Stops automatic execution of the garbage collector.
-The collector will run only when explicitly invoked,
-until a call to restart it.
-}
-
-@item{@St{restart}|
-Restarts automatic execution of the garbage collector.
-}
-
-@item{@St{count}|
-Returns the total memory in use by Lua in Kbytes.
-The value has a fractional part,
-so that it multiplied by 1024
-gives the exact number of bytes in use by Lua.
-}
-
-@item{@St{step}|
-Performs a garbage-collection step.
-This option may be followed by an extra argument,
-an integer with the step size.
-
-If the size is a positive @id{n},
-the collector acts as if @id{n} new bytes have been allocated.
-If the size is zero,
-the collector performs a basic step.
-In incremental mode,
-a basic step corresponds to the current step size.
-In generational mode,
-a basic step performs a full minor collection or
-an incremental step,
-if the collector has scheduled one.
-
-In incremental mode,
-the function returns @true if the step finished a collection cycle.
-In generational mode,
-the function returns @true if the step finished a major collection.
-}
-
-@item{@St{isrunning}|
-Returns a boolean that tells whether the collector is running
-(i.e., not stopped).
-}
-
-@item{@St{incremental}|
-Changes the collector mode to incremental and returns the previous mode.
-}
-
-@item{@St{generational}|
-Changes the collector mode to generational and returns the previous mode.
-}
-
-@item{@St{param}|
-Changes and/or retrieves the values of a parameter of the collector.
-This option must be followed by one or two extra arguments:
-The name of the parameter being changed or retrieved (a string)
-and an optional new value for that parameter,
-an integer in the range @M{[0,100000]}.
-The first argument must have one of the following values:
-@description{
-@item{@St{minormul}| The minor multiplier. }
-@item{@St{majorminor}| The major-minor multiplier. }
-@item{@St{minormajor}| The minor-major multiplier. }
-@item{@St{pause}| The garbage-collector pause. }
-@item{@St{stepmul}| The step multiplier. }
-@item{@St{stepsize}| The step size. }
-}
-The call always returns the previous value of the parameter.
-If the call does not give a new value,
-the value is left unchanged.
-
-Lua stores these values in a compressed format,
-so, the value returned as the previous value may not be
-exactly the last value set.
-}
-
-}
-See @See{GC} for more details about garbage collection
-and some of these options.
-
-This function should not be called by a finalizer.
-
-}
-
-@LibEntry{dofile ([filename])|
-Opens the named file and executes its content as a Lua chunk,
-returning all values returned by the chunk.
-When called without arguments,
-@id{dofile} executes the content of the standard input (@id{stdin}).
-In case of errors, @id{dofile} propagates the error
-to its caller.
-(That is, @id{dofile} does not run in protected mode.)
-
-}
-
-@LibEntry{error (message [, level])|
-Raises an error @see{error} with @id{message} as the error object.
-This function never returns.
-
-Usually, @id{error} adds some information about the error position
-at the beginning of the message, if the message is a string.
-The @id{level} argument specifies how to get the error position.
-With @N{level 1} (the default), the error position is where the
-@id{error} function was called.
-@N{Level 2} points the error to where the function
-that called @id{error} was called; and so on.
-Passing a @N{level 0} avoids the addition of error position information
-to the message.
-
-}
-
-@LibEntry{_G|
-A global variable (not a function) that
-holds the @x{global environment} @see{globalenv}.
-Lua itself does not use this variable;
-changing its value does not affect any environment,
-nor vice versa.
-
-}
-
-@LibEntry{getmetatable (object)|
-
-If @id{object} does not have a metatable, returns @nil.
-Otherwise,
-if the object's metatable has a @idx{__metatable} field,
-returns the associated value.
-Otherwise, returns the metatable of the given object.
-
-}
-
-@LibEntry{ipairs (t)|
-
-Returns three values (an iterator function, the value @id{t}, and 0)
-so that the construction
-@verbatim{
-for i,v in ipairs(t) do @rep{body} end
-}
-will iterate over the key@En{}value pairs
-(@T{1,t[1]}), (@T{2,t[2]}), @ldots,
-up to the first absent index.
-
-}
-
-@LibEntry{load (chunk [, chunkname [, mode [, env]]])|
-
-Loads a chunk.
-
-If @id{chunk} is a string, the chunk is this string.
-If @id{chunk} is a function,
-@id{load} calls it repeatedly to get the chunk pieces.
-Each call to @id{chunk} must return a string that concatenates
-with previous results.
-A return of an empty string, @nil, or no value signals the end of the chunk.
-
-If there are no syntactic errors,
-@id{load} returns the compiled chunk as a function;
-otherwise, it returns @fail plus the error message.
-
-When you load a main chunk,
-the resulting function will always have exactly one upvalue,
-the @id{_ENV} variable @see{globalenv}.
-However,
-when you load a binary chunk created from a function @seeF{string.dump},
-the resulting function can have an arbitrary number of upvalues,
-and there is no guarantee that its first upvalue will be
-the @id{_ENV} variable.
-(A non-main function may not even have an @id{_ENV} upvalue.)
-
-Regardless, if the resulting function has any upvalues,
-its first upvalue is set to the value of @id{env},
-if that parameter is given,
-or to the value of the @x{global environment}.
-Other upvalues are initialized with @nil.
-All upvalues are fresh, that is,
-they are not shared with any other function.
-
-@id{chunkname} is used as the name of the chunk for error messages
-and debug information @see{debugI}.
-When absent,
-it defaults to @id{chunk}, if @id{chunk} is a string,
-or to @St{=(load)} otherwise.
-
-The string @id{mode} controls whether the chunk can be text or binary
-(that is, a precompiled chunk).
-It may be the string @St{b} (only @x{binary chunk}s),
-@St{t} (only text chunks),
-or @St{bt} (both binary and text).
-The default is @St{bt}.
-
-Lua does not check the consistency of binary chunks.
-Maliciously crafted binary chunks can crash
-the interpreter.
-You can use the @id{mode} parameter to prevent loading binary chunks.
-
-}
-
-@LibEntry{loadfile ([filename [, mode [, env]]])|
-
-Similar to @Lid{load},
-but gets the chunk from file @id{filename}
-or from the standard input,
-if no file name is given.
-
-}
-
-@LibEntry{next (table [, index])|
-
-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 call to @id{next} returns the next index of the table
-and its associated value.
-When called with @nil as its second argument,
-@id{next} returns an initial index
-and its associated value.
-When called with the last index,
-or with @nil in an empty table,
-@id{next} returns @nil.
-If the second argument is absent, then it is interpreted as @nil.
-In particular,
-you can use @T{next(t)} to check whether a table is empty.
-
-The order in which the indices are enumerated is not specified,
-@emph{even for numeric indices}.
-(To traverse a table in numerical order,
-use a numerical @Rw{for}.)
-
-You should not assign any value to a non-existent field in a table
-during its traversal.
-You may however modify existing fields.
-In particular, you may set existing fields to nil.
-
-}
-
-@LibEntry{pairs (t)|
-
-If @id{t} has a metamethod @idx{__pairs},
-calls it with @id{t} as argument and returns the first four
-results from the call.
-
-Otherwise,
-returns the @Lid{next} function, the table @id{t}, plus two @nil values,
-so that the construction
-@verbatim{
-for k,v in pairs(t) do @rep{body} end
-}
-will iterate over all key@En{}value pairs of table @id{t}.
-
-See function @Lid{next} for the caveats of modifying
-the table during its traversal.
-
-}
-
-@LibEntry{pcall (f [, arg1, @Cdots])|
-
-Calls the function @id{f} with
-the given arguments in @emphx{protected mode}.
-This means that any error @N{inside @T{f}} is not propagated;
-instead, @id{pcall} 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, @id{pcall} also returns all results from the call,
-after this first result.
-In case of any error, @id{pcall} returns @false plus the error object.
-Note that errors caught by @id{pcall} do not call a message handler.
-
-}
-
-@LibEntry{print (@Cdots)|
-Receives any number of arguments
-and prints their values to @id{stdout},
-converting each argument to a string
-following the same rules of @Lid{tostring}.
-
-The function @id{print} is not intended for formatted output,
-but only as a quick way to show a value,
-for instance for debugging.
-For complete control over the output,
-use @Lid{string.format} and @Lid{io.write}.
-
-}
-
-@LibEntry{rawequal (v1, v2)|
-Checks whether @id{v1} is equal to @id{v2},
-without invoking the @idx{__eq} metamethod.
-Returns a boolean.
-
-}
-
-@LibEntry{rawget (table, index)|
-Gets the real value of @T{table[index]},
-without using the @idx{__index} metavalue.
-@id{table} must be a table;
-@id{index} may be any value.
-
-}
-
-@LibEntry{rawlen (v)|
-Returns the length of the object @id{v},
-which must be a table or a string,
-without invoking the @idx{__len} metamethod.
-Returns an integer.
-
-}
-
-@LibEntry{rawset (table, index, value)|
-Sets the real value of @T{table[index]} to @id{value},
-without using the @idx{__newindex} metavalue.
-@id{table} must be a table,
-@id{index} any value different from @nil and @x{NaN},
-and @id{value} any Lua value.
-
-This function returns @id{table}.
-
-}
-
-@LibEntry{select (index, @Cdots)|
-
-If @id{index} is a number,
-returns all arguments after argument number @id{index};
-a negative number indexes from the end (@num{-1} is the last argument).
-Otherwise, @id{index} must be the string @T{"#"},
-and @id{select} returns the total number of extra arguments it received.
-
-}
-
-@LibEntry{setmetatable (table, metatable)|
-
-Sets the metatable for the given table.
-If @id{metatable} is @nil,
-removes the metatable of the given table.
-If the original metatable has a @idx{__metatable} field,
-raises an error.
-
-This function returns @id{table}.
-
-To change the metatable of other types from Lua code,
-you must use the @link{debuglib|debug library}.
-
-}
-
-@LibEntry{tonumber (e [, base])|
-
-When called with no @id{base},
-@id{tonumber} tries to convert its argument to a number.
-If the argument is already a number or
-a string convertible to a number,
-then @id{tonumber} returns this number;
-otherwise, it returns @fail.
-
-The conversion of strings can result in integers or floats,
-according to the lexical conventions of Lua @see{lexical}.
-The string may have leading and trailing spaces and a sign.
-
-When called with @id{base},
-then @id{e} must be a string to be interpreted as
-an integer numeral in that base.
-The base may be any integer between 2 and 36, inclusive.
-In bases @N{above 10}, the letter @Char{A} (in either upper or lower case)
-@N{represents 10}, @Char{B} @N{represents 11}, and so forth,
-with @Char{Z} representing 35.
-If the string @id{e} is not a valid numeral in the given base,
-the function returns @fail.
-
-}
-
-@LibEntry{tostring (v)|
-
-Receives a value of any type and
-converts it to a string in a human-readable format.
-
-If the metatable of @id{v} has a @idx{__tostring} field,
-then @id{tostring} calls the corresponding value
-with @id{v} as argument,
-and uses the result of the call as its result.
-Otherwise, if the metatable of @id{v} has a @idx{__name} field
-with a string value,
-@id{tostring} may use that string in its final result.
-
-For complete control of how numbers are converted,
-use @Lid{string.format}.
-
-}
-
-@LibEntry{type (v)|
-
-Returns the type of its only argument, coded as a string.
-The possible results of this function are
-@St{nil} (a string, not the value @nil),
-@St{number},
-@St{string},
-@St{boolean},
-@St{table},
-@St{function},
-@St{thread},
-and @St{userdata}.
-
-}
-
-@LibEntry{_VERSION|
-
-A global variable (not a function) that
-holds a string containing the running Lua version.
-The current value of this variable is @St{Lua 5.5}.
-
-}
-
-@LibEntry{warn (msg1, @Cdots)|
-
-Emits a warning with a message composed by the concatenation
-of all its arguments (which should be strings).
-
-By convention,
-a one-piece message starting with @Char{@At}
-is intended to be a @emph{control message},
-which is a message to the warning system itself.
-In particular, the standard warning function in Lua
-recognizes the control messages @St{@At{}off},
-to stop the emission of warnings,
-and @St{@At{}on}, to (re)start the emission;
-it ignores unknown control messages.
-
-}
-
-@LibEntry{xpcall (f, msgh [, arg1, @Cdots])|
-
-This function is similar to @Lid{pcall},
-except that it sets a new @x{message handler} @id{msgh}.
-
-}
-
-}
-
-@sect2{corolib| @title{Coroutine Manipulation}
-
-This library comprises the operations to manipulate coroutines,
-which come inside the table @defid{coroutine}.
-See @See{coroutine} for a general description of coroutines.
-
-
-@LibEntry{coroutine.close ([co])|
-
-Closes coroutine @id{co},
-that is,
-closes all its pending to-be-closed variables
-and puts the coroutine in a dead state.
-The default for @id{co} is the running coroutine.
-
-The given coroutine must be dead, suspended,
-or be the running coroutine.
-For the running coroutine,
-this function does not return.
-Instead, the resume that (re)started the coroutine returns.
-
-For other coroutines,
-in case of error
-(either the original error that stopped the coroutine or
-errors in closing methods),
-this function returns @false plus the error object;
-otherwise it returns @true.
-
-}
-
-@LibEntry{coroutine.create (f)|
-
-Creates a new coroutine, with body @id{f}.
-@id{f} must be a function.
-Returns this new coroutine,
-an object with type @T{"thread"}.
-
-}
-
-@LibEntry{coroutine.isyieldable ([co])|
-
-Returns @true when the coroutine @id{co} can yield.
-The default for @id{co} is the running coroutine.
-
-A coroutine is yieldable if it is not the main thread and
-it is not inside a non-yieldable @N{C function}.
-
-}
-
-@LibEntry{coroutine.resume (co [, val1, @Cdots])|
-
-Starts or continues the execution of coroutine @id{co}.
-The first time you resume a coroutine,
-it starts running its body.
-The values @id{val1}, @ldots are passed
-as the arguments to the body function.
-If the coroutine has yielded,
-@id{resume} restarts it;
-the values @id{val1}, @ldots are passed
-as the results from the yield.
-
-If the coroutine runs without any errors,
-@id{resume} returns @true plus any values passed to @id{yield}
-(when the coroutine yields) or any values returned by the body function
-(when the coroutine terminates).
-If there is any error,
-@id{resume} returns @false plus the error message.
-
-}
-
-@LibEntry{coroutine.running ()|
-
-Returns the running coroutine plus a boolean,
-@true when the running coroutine is the main one.
-
-}
-
-@LibEntry{coroutine.status (co)|
-
-Returns the status of the coroutine @id{co}, as a string:
-@T{"running"},
-if the coroutine is running
-(that is, it is the one that called @id{status});
-@T{"suspended"}, if the coroutine is suspended in a call to @id{yield},
-or if it has not started running yet;
-@T{"normal"} if the coroutine is active but not running
-(that is, it has resumed another coroutine);
-and @T{"dead"} if the coroutine has finished its body function,
-or if it has stopped with an error.
-
-}
-
-@LibEntry{coroutine.wrap (f)|
-
-Creates a new coroutine, with body @id{f};
-@id{f} must be a function.
-Returns a function that resumes the coroutine each time it is called.
-Any arguments passed to this function behave as the
-extra arguments to @id{resume}.
-The function returns the same values returned by @id{resume},
-except the first boolean.
-In case of error,
-the function closes the coroutine and propagates the error.
-
-}
-
-@LibEntry{coroutine.yield (@Cdots)|
-
-Suspends the execution of the calling coroutine.
-Any arguments to @id{yield} are passed as extra results to @id{resume}.
-
-}
-
-}
-
-@sect2{packlib| @title{Modules}
-
-The package library provides basic
-facilities for loading modules in Lua.
-It exports one function directly in the global environment:
-@Lid{require}.
-Everything else is exported in the table @defid{package}.
-
-
-@LibEntry{require (modname)|
-
-Loads the given module.
-The function starts by looking into the @Lid{package.loaded} table
-to determine whether @id{modname} is already loaded.
-If it is, then @id{require} returns the value stored
-at @T{package.loaded[modname]}.
-(The absence of a second result in this case
-signals that this call did not have to load the module.)
-Otherwise, it tries to find a @emph{loader} for the module.
-
-To find a loader,
-@id{require} is guided by the table @Lid{package.searchers}.
-Each item in this table is a search function,
-that searches for the module in a particular way.
-By changing this table,
-we can change how @id{require} looks for a module.
-The following explanation is based on the default configuration
-for @Lid{package.searchers}.
-
-First @id{require} queries @T{package.preload[modname]}.
-If it has a value,
-this value (which must be a function) is the loader.
-Otherwise @id{require} searches for a Lua loader using the
-path stored in @Lid{package.path}.
-If that also fails, it searches for a @N{C loader} using the
-path stored in @Lid{package.cpath}.
-If that also fails,
-it tries an @emph{all-in-one} loader @seeF{package.searchers}.
-
-Once a loader is found,
-@id{require} calls the loader with two arguments:
-@id{modname} and an extra value,
-a @emph{loader data},
-also returned by the searcher.
-The loader data can be any value useful to the module;
-for the default searchers,
-it indicates where the loader was found.
-(For instance, if the loader came from a file,
-this extra value is the file path.)
-If the loader returns any non-nil value,
-@id{require} assigns the returned value to @T{package.loaded[modname]}.
-If the loader does not return a non-nil value and
-has not assigned any value to @T{package.loaded[modname]},
-then @id{require} assigns @true to this entry.
-In any case, @id{require} returns the
-final value of @T{package.loaded[modname]}.
-Besides that value, @id{require} also returns as a second result
-the loader data returned by the searcher,
-which indicates how @id{require} found the module.
-
-If there is any error loading or running the module,
-or if it cannot find any loader for the module,
-then @id{require} raises an error.
-
-}
-
-@LibEntry{package.config|
-
-A string describing some compile-time configurations for packages.
-This string is a sequence of lines:
-@itemize{
-
-@item{The first line is the @x{directory separator} string.
-Default is @Char{\} for @x{Windows} and @Char{/} for all other systems.}
-
-@item{The second line is the character that separates templates in a path.
-Default is @Char{;}.}
-
-@item{The third line is the string that marks the
-substitution points in a template.
-Default is @Char{?}.}
-
-@item{The fourth line is a string that, in a path in @x{Windows},
-is replaced by the executable's directory.
-Default is @Char{!}.}
-
-@item{The fifth line is a mark to ignore all text after it
-when building the @id{luaopen_} function name.
-Default is @Char{-}.}
-
-}
-
-}
-
-@LibEntry{package.cpath|
-
-A string with the path used by @Lid{require}
-to search for a @N{C loader}.
-
-Lua initializes the @N{C path} @Lid{package.cpath} in the same way
-it initializes the Lua path @Lid{package.path},
-using the environment variable @defid{LUA_CPATH_5_5},
-or the environment variable @defid{LUA_CPATH},
-or a default path defined in @id{luaconf.h}.
-
-}
-
-@LibEntry{package.loaded|
-
-A table used by @Lid{require} to control which
-modules are already loaded.
-When you require a module @id{modname} and
-@T{package.loaded[modname]} is not false,
-@Lid{require} simply returns the value stored there.
-
-This variable is only a reference to the real table;
-assignments to this variable do not change the
-table used by @Lid{require}.
-The real table is stored in the C registry @see{registry},
-indexed by the key @defid{LUA_LOADED_TABLE}, a string.
-
-}
-
-@LibEntry{package.loadlib (libname, funcname)|
-
-Dynamically links the host program with the @N{C library} @id{libname}.
-
-If @id{funcname} is @St{*},
-then it only links with the library,
-making the symbols exported by the library
-available to other dynamically linked libraries.
-Otherwise,
-it looks for a function @id{funcname} inside the library
-and returns this function as a @N{C function}.
-So, @id{funcname} must follow the @Lid{lua_CFunction} prototype
-@seeC{lua_CFunction}.
-
-This is a low-level function.
-It completely bypasses the package and module system.
-Unlike @Lid{require},
-it does not perform any path searching and
-does not automatically adds extensions.
-@id{libname} must be the complete file name of the @N{C library},
-including if necessary a path and an extension.
-@id{funcname} must be the exact name exported by the @N{C library}
-(which may depend on the @N{C compiler} and linker used).
-
-This functionality is not supported by @N{ISO C}.
-As such, @id{loadlib} is only available on some platforms:
-Linux, Windows, Mac OS X, Solaris, BSD,
-plus other Unix systems that support the @id{dlfcn} standard.
-
-This function is inherently insecure,
-as it allows Lua to call any function in any readable dynamic
-library in the system.
-(Lua calls any function assuming the function
-has a proper prototype and respects a proper protocol
-@see{lua_CFunction}.
-Therefore,
-calling an arbitrary function in an arbitrary dynamic library
-more often than not results in an access violation.)
-
-}
-
-@LibEntry{package.path|
-
-A string with the path used by @Lid{require}
-to search for a Lua loader.
-
-At start-up, Lua initializes this variable with
-the value of the environment variable @defid{LUA_PATH_5_5} or
-the environment variable @defid{LUA_PATH} or
-with a default path defined in @id{luaconf.h},
-if those environment variables are not defined.
-A @St{;;} in the value of the environment variable
-is replaced by the default path.
-
-}
-
-@LibEntry{package.preload|
-
-A table to store loaders for specific modules
-@seeF{require}.
-
-This variable is only a reference to the real table;
-assignments to this variable do not change the
-table used by @Lid{require}.
-The real table is stored in the C registry @see{registry},
-indexed by the key @defid{LUA_PRELOAD_TABLE}, a string.
-
-}
-
-@LibEntry{package.searchers|
-
-A table used by @Lid{require} to control how to find modules.
-
-Each entry in this table is a @def{searcher function}.
-When looking for a module,
-@Lid{require} calls each of these searchers in ascending order,
-with the module name (the argument given to @Lid{require}) as its
-sole argument.
-If the searcher finds the module,
-it returns another function, the module @def{loader},
-plus an extra value, a @emph{loader data},
-that will be passed to that loader and
-returned as a second result by @Lid{require}.
-If it cannot find the module,
-it returns a string explaining why
-(or @nil if it has nothing to say).
-
-Lua initializes this table with four searcher functions.
-
-The first searcher simply looks for a loader in the
-@Lid{package.preload} table.
-
-The second searcher looks for a loader as a Lua library,
-using the path stored at @Lid{package.path}.
-The search is done as described in function @Lid{package.searchpath}.
-
-The third searcher looks for a loader as a @N{C library},
-using the path given by the variable @Lid{package.cpath}.
-Again,
-the search is done as described in function @Lid{package.searchpath}.
-For instance,
-if the @N{C path} is the string
-@verbatim{
-"./?.so;./?.dll;/usr/local/?/init.so"
-}
-the searcher for module @id{foo}
-will try to open the files @T{./foo.so}, @T{./foo.dll},
-and @T{/usr/local/foo/init.so}, in that order.
-Once it finds a @N{C library},
-this searcher first uses a dynamic link facility to link the
-application with the library.
-Then it tries to find a @N{C function} inside the library to
-be used as the loader.
-The name of this @N{C function} is the string @St{luaopen_}
-concatenated with a copy of the module name where each dot
-is replaced by an underscore.
-Moreover, if the module name has a hyphen,
-its suffix after (and including) the first hyphen is removed.
-For instance, if the module name is @id{a.b.c-v2.1},
-the function name will be @id{luaopen_a_b_c}.
-
-The fourth searcher tries an @def{all-in-one loader}.
-It searches the @N{C path} for a library for
-the root name of the given module.
-For instance, when requiring @id{a.b.c},
-it will search for a @N{C library} for @id{a}.
-If found, it looks into it for an open function for
-the submodule;
-in our example, that would be @id{luaopen_a_b_c}.
-With this facility, a package can pack several @N{C submodules}
-into one single library,
-with each submodule keeping its original open function.
-
-All searchers except the first one (preload) return as the extra value
-the file path where the module was found,
-as returned by @Lid{package.searchpath}.
-The first searcher always returns the string @St{:preload:}.
-
-Searchers should raise no errors and have no side effects in Lua.
-(They may have side effects in C,
-for instance by linking the application with a library.)
-
-}
-
-@LibEntry{package.searchpath (name, path [, sep [, rep]])|
-
-Searches for the given @id{name} in the given @id{path}.
-
-A path is a string containing a sequence of
-@emph{templates} separated by semicolons.
-For each template,
-the function replaces each interrogation mark (if any)
-in the template with a copy of @id{name}
-wherein all occurrences of @id{sep}
-(a dot, by default)
-were replaced by @id{rep}
-(the system's directory separator, by default),
-and then tries to open the resulting file name.
-
-For instance, if the path is the string
-@verbatim{
-"./?.lua;./?.lc;/usr/local/?/init.lua"
-}
-the search for the name @id{foo.a}
-will try to open the files
-@T{./foo/a.lua}, @T{./foo/a.lc}, and
-@T{/usr/local/foo/a/init.lua}, in that order.
-
-Returns the resulting name of the first file that it can
-open in read mode (after closing the file),
-or @fail plus an error message if none succeeds.
-(This error message lists all file names it tried to open.)
-
-}
-
-}
-
-@sect2{strlib| @title{String Manipulation}
-
-@simplesect{
-
-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 @N{position 1}
-(not @N{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 @num{-1}, and so on.
-
-The string library provides all its functions inside the table
-@defid{string}.
-It also sets a @x{metatable for strings}
-where the @idx{__index} field points to the @id{string} table.
-Therefore, you can use the string functions in object-oriented style.
-For instance, @T{string.byte(s,i)}
-can be written as @T{s:byte(i)}.
-
-The string library assumes one-byte character encodings.
-
-
-@LibEntry{string.byte (s [, i [, j]])|
-Returns the internal numeric codes of the characters @T{s[i]},
-@T{s[i+1]}, @ldots, @T{s[j]}.
-The default value for @id{i} @N{is 1};
-the default value for @id{j} @N{is @id{i}}.
-These indices are corrected
-following the same rules of function @Lid{string.sub}.
-
-Numeric codes are not necessarily portable across platforms.
-
-}
-
-@LibEntry{string.char (@Cdots)|
-Receives zero or more integers.
-Returns a string with length equal to the number of arguments,
-in which each character has the internal numeric code equal
-to its corresponding argument.
-
-Numeric codes are not necessarily portable across platforms.
-
-}
-
-@LibEntry{string.dump (function [, strip])|
-
-Returns a string containing a binary representation
-(a @emph{binary chunk})
-of the given function,
-so that a later @Lid{load} on this string returns
-a copy of the function (but with new upvalues).
-If @id{strip} is a true value,
-the binary representation may not include all debug information
-about the function,
-to save space.
-
-Functions with upvalues have only their number of upvalues saved.
-When (re)loaded,
-those upvalues receive fresh instances.
-(See the @Lid{load} function for details about
-how these upvalues are initialized.
-You can use the debug library to serialize
-and reload the upvalues of a function
-in a way adequate to your needs.)
-
-}
-
-@LibEntry{string.find (s, pattern [, init [, plain]])|
-
-Looks for the first match of
-@id{pattern} @see{pm} in the string @id{s}.
-If it finds a match, then @id{find} returns the indices @N{of @T{s}}
-where this occurrence starts and ends;
-otherwise, it returns @fail.
-A third, optional numeric argument @id{init} specifies
-where to start the search;
-its default value @N{is 1} and can be negative.
-A @true as a fourth, optional argument @id{plain}
-turns off the pattern matching facilities,
-so the function does a plain @Q{find substring} operation,
-with no characters in @id{pattern} being considered magic.
-
-If the pattern has captures,
-then in a successful match
-the captured values are also returned,
-after the two indices.
-
-}
-
-@LibEntry{string.format (formatstring, @Cdots)|
-
-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 @ANSI{sprintf}.
-The accepted conversion specifiers are
-@id{A}, @id{a}, @id{c}, @id{d}, @id{E}, @id{e}, @id{f}, @id{G}, @id{g},
-@id{i}, @id{o}, @id{p}, @id{s}, @id{u}, @id{X}, @id{x}, and @Char{%},
-plus a non-C specifier @id{q}.
-The accepted flags are @Char{-}, @Char{+}, @Char{#},
-@Char{0}, and @Char{ } (space).
-Both width and precision, when present,
-are limited to two digits.
-
-The specifier @id{q} formats booleans, nil, numbers, and strings
-in a way that the result is a valid constant in Lua source code.
-Booleans and nil are written in the obvious way
-(@id{true}, @id{false}, @id{nil}).
-Floats are written in hexadecimal,
-to preserve full precision.
-A string is written between double quotes,
-using escape sequences when necessary to ensure that
-it can safely be read back by the Lua interpreter.
-For instance, the call
-@verbatim{
-string.format('%q', 'a string with "quotes" and \n new line')
-}
-may produce the string:
-@verbatim{
-"a string with \"quotes\" and \
- new line"
-}
-This specifier does not support modifiers (flags, width, precision).
-
-The conversion specifiers
-@id{A}, @id{a}, @id{E}, @id{e}, @id{f},
-@id{G}, and @id{g} all expect a number as argument.
-The specifiers @id{c}, @id{d},
-@id{i}, @id{o}, @id{u}, @id{X}, and @id{x}
-expect an integer.
-When Lua is compiled with a C89 compiler,
-the specifiers @id{A} and @id{a} (hexadecimal floats)
-do not support modifiers.
-
-The specifier @id{s} expects a string;
-if its argument is not a string,
-it is converted to one following the same rules of @Lid{tostring}.
-If the specifier has any modifier,
-the corresponding string argument should not contain @x{embedded zeros}.
-
-The specifier @id{p} formats the pointer
-returned by @Lid{lua_topointer}.
-That gives a unique string identifier for tables, userdata,
-threads, strings, and functions.
-For other values (numbers, nil, booleans),
-this specifier results in a string representing
-the pointer @id{NULL}.
-
-}
-
-@LibEntry{string.gmatch (s, pattern [, init])|
-Returns an iterator function that,
-each time it is called,
-returns the next captures from @id{pattern} @see{pm}
-over the string @id{s}.
-If @id{pattern} specifies no captures,
-then the whole match is produced in each call.
-A third, optional numeric argument @id{init} specifies
-where to start the search;
-its default value @N{is 1} and can be negative.
-
-As an example, the following loop
-will iterate over all the words from string @id{s},
-printing one per line:
-@verbatim{
-s = "hello world from Lua"
-for w in string.gmatch(s, "%a+") do
- print(w)
-end
-}
-The next example collects all pairs @T{key=value} from the
-given string into a table:
-@verbatim{
-t = {}
-s = "from=world, to=Lua"
-for k, v in string.gmatch(s, "(%w+)=(%w+)") do
- t[k] = v
-end
-}
-
-For this function, a caret @Char{^} at the start of a pattern does not
-work as an anchor, as this would prevent the iteration.
-
-}
-
-@LibEntry{string.gsub (s, pattern, repl [, n])|
-Returns a copy of @id{s}
-in which all (or the first @id{n}, if given)
-occurrences of the @id{pattern} @see{pm} have been
-replaced by a replacement string specified by @id{repl},
-which can be a string, a table, or a function.
-@id{gsub} also returns, as its second value,
-the total number of matches that occurred.
-The name @id{gsub} comes from @emph{Global SUBstitution}.
-
-If @id{repl} is a string, then its value is used for replacement.
-The @N{character @T{%}} works as an escape character:
-any sequence in @id{repl} of the form @T{%@rep{d}},
-with @rep{d} between 1 and 9,
-stands for the value of the @rep{d}-th captured substring;
-the sequence @T{%0} stands for the whole match;
-the sequence @T{%%} stands for a @N{single @T{%}}.
-
-If @id{repl} is a table, then the table is queried for every match,
-using the first capture as the key.
-
-If @id{repl} is a function, then this function is called every time a
-match occurs, with all captured substrings passed as arguments,
-in order.
-
-In any case,
-if the pattern specifies no captures,
-then it behaves as if the whole pattern was inside a capture.
-
-If the value returned by the table query or by the function call
-is a string or a number,
-then it is used as the replacement string;
-otherwise, if it is @Rw{false} or @nil,
-then there is no replacement
-(that is, the original match is kept in the string).
-
-Here are some examples:
-@verbatim{
-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 load(s)()
- end)
--- x="4+5 = 9"
-
-local t = {name="lua", version="5.5"}
-x = string.gsub("$name-$version.tar.gz", "%$(%w+)", t)
--- x="lua-5.5.tar.gz"
-}
-
-}
-
-@LibEntry{string.len (s)|
-
-Receives a string and returns its length.
-The empty string @T{""} has length 0.
-Embedded zeros are counted,
-so @T{"a\000bc\000"} has length 5.
-
-}
-
-@LibEntry{string.lower (s)|
-
-Receives a string and returns a copy of this string with all
-uppercase letters changed to lowercase.
-All other characters are left unchanged.
-The definition of what an uppercase letter is depends on the current locale.
-
-}
-
-@LibEntry{string.match (s, pattern [, init])|
-
-Looks for the first @emph{match} of
-the @id{pattern} @see{pm} in the string @id{s}.
-If it finds one, then @id{match} returns
-the captures from the pattern;
-otherwise it returns @fail.
-If @id{pattern} specifies no captures,
-then the whole match is returned.
-A third, optional numeric argument @id{init} specifies
-where to start the search;
-its default value @N{is 1} and can be negative.
-
-}
-
-@LibEntry{string.pack (fmt, v1, v2, @Cdots)|
-
-Returns a binary string containing the values @id{v1}, @id{v2}, etc.
-serialized in binary form (packed)
-according to the format string @id{fmt} @see{pack}.
-
-}
-
-@LibEntry{string.packsize (fmt)|
-
-Returns the length of a string resulting from @Lid{string.pack}
-with the given format.
-The format string cannot have the variable-length options
-@Char{s} or @Char{z} @see{pack}.
-
-}
-
-@LibEntry{string.rep (s, n [, sep])|
-
-Returns a string that is the concatenation of @id{n} copies of
-the string @id{s} separated by the string @id{sep}.
-The default value for @id{sep} is the empty string
-(that is, no separator).
-Returns the empty string if @id{n} is not positive.
-
-(Note that it is very easy to exhaust the memory of your machine
-with a single call to this function.)
-
-}
-
-@LibEntry{string.reverse (s)|
-
-Returns a string that is the string @id{s} reversed.
-
-}
-
-@LibEntry{string.sub (s, i [, j])|
-
-Returns the substring of @id{s} that
-starts at @id{i} and continues until @id{j};
-@id{i} and @id{j} can be negative.
-If @id{j} is absent, then it is assumed to be equal to @num{-1}
-(which is the same as the string length).
-In particular,
-the call @T{string.sub(s,1,j)} returns a prefix of @id{s}
-with length @id{j},
-and @T{string.sub(s,-i)} (for a positive @id{i})
-returns a suffix of @id{s}
-with length @id{i}.
-
-If, after the translation of negative indices,
-@id{i} is less than 1,
-it is corrected to 1.
-If @id{j} is greater than the string length,
-it is corrected to that length.
-If, after these corrections,
-@id{i} is greater than @id{j},
-the function returns the empty string.
-
-}
-
-@LibEntry{string.unpack (fmt, s [, pos])|
-
-Returns the values packed in string @id{s} @seeF{string.pack}
-according to the format string @id{fmt} @see{pack}.
-An optional @id{pos} marks where
-to start reading in @id{s} (default is 1).
-After the read values,
-this function also returns the index of the first unread byte in @id{s}.
-
-}
-
-@LibEntry{string.upper (s)|
-
-Receives a string and returns a copy of this string with all
-lowercase letters changed to uppercase.
-All other characters are left unchanged.
-The definition of what a lowercase letter is depends on the current locale.
-
-}
-
-}
-
-
-@sect3{pm| @title{Patterns}
-
-@simplesect{
-
-Patterns in Lua are described by regular strings,
-which are interpreted as patterns by the pattern-matching functions
-@Lid{string.find},
-@Lid{string.gmatch},
-@Lid{string.gsub},
-and @Lid{string.match}.
-This section describes the syntax and the meaning
-(that is, what they match) of these strings.
-
-}
-
-@sect4{@title{Character Class:}
-A @def{character class} is used to represent a set of characters.
-The following combinations are allowed in describing a character class:
-@description{
-
-@item{@rep{x}|
-(where @rep{x} is not one of the @emphx{magic characters}
-@T{^$()%.[]*+-?})
-represents the character @emph{x} itself.
-}
-
-@item{@T{.}| (a dot) represents all characters.}
-
-@item{@T{%a}| represents all letters.}
-
-@item{@T{%c}| represents all control characters.}
-
-@item{@T{%d}| represents all digits.}
-
-@item{@T{%g}| represents all printable characters except space.}
-
-@item{@T{%l}| represents all lowercase letters.}
-
-@item{@T{%p}| represents all punctuation characters.}
-
-@item{@T{%s}| represents all space characters.}
-
-@item{@T{%u}| represents all uppercase letters.}
-
-@item{@T{%w}| represents all alphanumeric characters.}
-
-@item{@T{%x}| represents all hexadecimal digits.}
-
-@item{@T{%@rep{x}}| (where @rep{x} is any non-alphanumeric character)
-represents the character @rep{x}.
-This is the standard way to escape the magic characters.
-Any non-alphanumeric character
-(including all punctuation characters, even the non-magical)
-can be preceded by a @Char{%} to represent itself in a pattern.
-}
-
-@item{@T{[@rep{set}]}|
-represents the class which is the union of all
-characters in @rep{set}.
-A range of characters can be specified by
-separating the end characters of the range,
-in ascending order, with a @Char{-}.
-All classes @T{%}@emph{x} described above can also be used as
-components in @rep{set}.
-All other characters in @rep{set} represent themselves.
-For example, @T{[%w_]} (or @T{[_%w]})
-represents all alphanumeric characters plus the underscore,
-@T{[0-7]} represents the octal digits,
-and @T{[0-7%l%-]} represents the octal digits plus
-the lowercase letters plus the @Char{-} character.
-
-You can put a closing square bracket in a set
-by positioning it as the first character in the set.
-You can put a hyphen in a set
-by positioning it as the first or the last character in the set.
-(You can also use an escape for both cases.)
-
-The interaction between ranges and classes is not defined.
-Therefore, patterns like @T{[%a-z]} or @T{[a-%%]}
-have no meaning.
-}
-
-@item{@T{[^@rep{set}]}|
-represents the complement of @rep{set},
-where @rep{set} is interpreted as above.
-}
-
-}
-For all classes represented by single letters (@T{%a}, @T{%c}, etc.),
-the corresponding uppercase letter represents the complement of the class.
-For instance, @T{%S} represents all non-space characters.
-
-The definitions of letter, space, and other character groups
-depend on the current locale.
-In particular, the class @T{[a-z]} may not be equivalent to @T{%l}.
-
-}
-
-@sect4{@title{Pattern Item:}
-A @def{pattern item} can be
-@itemize{
-
-@item{
-a single character class,
-which matches any single character in the class;
-}
-
-@item{
-a single character class followed by @Char{*},
-which matches sequences of zero or more characters in the class.
-These repetition items will always match the longest possible sequence;
-}
-
-@item{
-a single character class followed by @Char{+},
-which matches sequences of one or more characters in the class.
-These repetition items will always match the longest possible sequence;
-}
-
-@item{
-a single character class followed by @Char{-},
-which also matches sequences of zero or more characters in the class.
-Unlike @Char{*},
-these repetition items will always match the shortest possible sequence;
-}
-
-@item{
-a single character class followed by @Char{?},
-which matches zero or one occurrence of a character in the class.
-It always matches one occurrence if possible;
-}
-
-@item{
-@T{%@rep{n}}, for @rep{n} between 1 and 9;
-such item matches a substring equal to the @rep{n}-th captured string
-(see below);
-}
-
-@item{
-@T{%b@rep{xy}}, where @rep{x} and @rep{y} are two distinct characters;
-such item matches strings that start @N{with @rep{x}}, end @N{with @rep{y}},
-and where the @rep{x} and @rep{y} are @emph{balanced}.
-This means that, if one reads the string from left to right,
-counting @M{+1} for an @rep{x} and @M{-1} for a @rep{y},
-the ending @rep{y} is the first @rep{y} where the count reaches 0.
-For instance, the item @T{%b()} matches expressions with
-balanced parentheses.
-}
-
-@item{
-@T{%f[@rep{set}]}, a @def{frontier pattern};
-such item matches an empty string at any position such that
-the next character belongs to @rep{set}
-and the previous character does not belong to @rep{set}.
-The set @rep{set} is interpreted as previously described.
-The beginning and the end of the subject are handled as if
-they were the character @Char{\0}.
-}
-
-}
-
-}
-
-@sect4{@title{Pattern:}
-A @def{pattern} is a sequence of pattern items.
-A caret @Char{^} at the beginning of a pattern anchors the match at the
-beginning of the subject string.
-A @Char{$} at the end of a pattern anchors the match at the
-end of the subject string.
-At other positions,
-@Char{^} and @Char{$} have no special meaning and represent themselves.
-
-}
-
-@sect4{@title{Captures:}
-A pattern can contain sub-patterns enclosed in parentheses;
-they describe @def{captures}.
-When a match succeeds, the substrings of the subject string
-that match captures are stored (@emph{captured}) for future use.
-Captures are numbered according to their left parentheses.
-For instance, in the pattern @T{"(a*(.)%w(%s*))"},
-the part of the string matching @T{"a*(.)%w(%s*)"} is
-stored as the first capture, and therefore has @N{number 1};
-the character matching @St{.} is captured with @N{number 2},
-and the part matching @St{%s*} has @N{number 3}.
-
-As a special case, the capture @T{()} captures
-the current string position (a number).
-For instance, if we apply the pattern @T{"()aa()"} on the
-string @T{"flaaap"}, there will be two captures: @N{3 and 5}.
-
-}
-
-@sect4{@title{Multiple matches:}
-The function @Lid{string.gsub} and the iterator @Lid{string.gmatch}
-match multiple occurrences of the given pattern in the subject.
-For these functions,
-a new match is considered valid only
-if it ends at least one byte after the end of the previous match.
-In other words, the pattern machine never accepts the
-empty string as a match immediately after another match.
-As an example,
-consider the results of the following code:
-@verbatim{
-> string.gsub("abc", "()a*()", print);
---> 1 2
---> 3 3
---> 4 4
-}
-The second and third results come from Lua matching an empty
-string after @Char{b} and another one after @Char{c}.
-Lua does not match an empty string after @Char{a},
-because it would end at the same position of the previous match.
-
-}
-
-}
-
-@sect3{pack| @title{Format Strings for Pack and Unpack}
-
-The first argument to @Lid{string.pack},
-@Lid{string.packsize}, and @Lid{string.unpack}
-is a format string,
-which describes the layout of the structure being created or read.
-
-A format string is a sequence of conversion options.
-The conversion options are as follows:
-@description{
-@item{@T{<}|sets little endian}
-@item{@T{>}|sets big endian}
-@item{@T{=}|sets native endian}
-@item{@T{![@rep{n}]}|sets maximum alignment to @id{n}
-(default is native alignment)}
-@item{@T{b}|a signed byte (@id{char})}
-@item{@T{B}|an unsigned byte (@id{char})}
-@item{@T{h}|a signed @id{short} (native size)}
-@item{@T{H}|an unsigned @id{short} (native size)}
-@item{@T{l}|a signed @id{long} (native size)}
-@item{@T{L}|an unsigned @id{long} (native size)}
-@item{@T{j}|a @id{lua_Integer}}
-@item{@T{J}|a @id{lua_Unsigned}}
-@item{@T{T}|a @id{size_t} (native size)}
-@item{@T{i[@rep{n}]}|a signed @id{int} with @id{n} bytes
-(default is native size)}
-@item{@T{I[@rep{n}]}|an unsigned @id{int} with @id{n} bytes
-(default is native size)}
-@item{@T{f}|a @id{float} (native size)}
-@item{@T{d}|a @id{double} (native size)}
-@item{@T{n}|a @id{lua_Number}}
-@item{@T{c@rep{n}}|a fixed-sized string with @id{n} bytes}
-@item{@T{z}|a zero-terminated string}
-@item{@T{s[@emph{n}]}|a string preceded by its length
-coded as an unsigned integer with @id{n} bytes
-(default is a @id{size_t})}
-@item{@T{x}|one byte of padding}
-@item{@T{X@rep{op}}|an empty item that aligns
-according to option @id{op}
-(which is otherwise ignored)}
-@item{@Char{ }|(space) ignored}
-}
-(A @St{[@rep{n}]} means an optional integral numeral.)
-Except for padding, spaces, and configurations
-(options @St{xX <=>!}),
-each option corresponds to an argument in @Lid{string.pack}
-or a result in @Lid{string.unpack}.
-
-For options @St{!@rep{n}}, @St{s@rep{n}}, @St{i@rep{n}}, and @St{I@rep{n}},
-@id{n} can be any integer between 1 and 16.
-All integral options check overflows;
-@Lid{string.pack} checks whether the given value fits in the given size;
-@Lid{string.unpack} checks whether the read value fits in a Lua integer.
-For the unsigned options,
-Lua integers are treated as unsigned values too.
-
-Any format string starts as if prefixed by @St{!1=},
-that is,
-with maximum alignment of 1 (no alignment)
-and native endianness.
-
-Native endianness assumes that the whole system is
-either big or little endian.
-The packing functions will not emulate correctly the behavior
-of mixed-endian formats.
-
-Alignment works as follows:
-For each option,
-the format gets extra padding until the data starts
-at an offset that is a multiple of the minimum between the
-option size and the maximum alignment;
-this minimum must be a power of 2.
-Options @St{c} and @St{z} are not aligned;
-option @St{s} follows the alignment of its starting integer.
-
-
-All padding is filled with zeros by @Lid{string.pack}
-and ignored by @Lid{string.unpack}.
-
-}
-
-}
-
-@sect2{utf8| @title{UTF-8 Support}
-
-This library provides basic support for @x{UTF-8} encoding.
-It provides all its functions inside the table @defid{utf8}.
-This library does not provide any support for @x{Unicode} other
-than the handling of the encoding.
-Any operation that needs the meaning of a character,
-such as character classification, is outside its scope.
-
-Unless stated otherwise,
-all functions that expect a byte position as a parameter
-assume that the given position is either the start of a byte sequence
-or one plus the length of the subject string.
-As in the string library,
-negative indices count from the end of the string.
-
-Functions that create byte sequences
-accept all values up to @T{0x7FFFFFFF},
-as defined in the original UTF-8 specification;
-that implies byte sequences of up to six bytes.
-
-Functions that interpret byte sequences only accept
-valid sequences (well formed and not overlong).
-By default, they only accept byte sequences
-that result in valid Unicode code points,
-rejecting values greater than @T{10FFFF} and surrogates.
-A boolean argument @id{lax}, when available,
-lifts these checks,
-so that all values up to @T{0x7FFFFFFF} are accepted.
-(Not well formed and overlong sequences are still rejected.)
-
-
-@LibEntry{utf8.char (@Cdots)|
-
-Receives zero or more integers,
-converts each one to its corresponding UTF-8 byte sequence
-and returns a string with the concatenation of all these sequences.
-
-}
-
-@LibEntry{utf8.charpattern|
-
-The pattern (a string, not a function) @St{[\0-\x7F\xC2-\xFD][\x80-\xBF]*}
-@see{pm},
-which matches exactly one UTF-8 byte sequence,
-assuming that the subject is a valid UTF-8 string.
-
-}
-
-@LibEntry{utf8.codes (s [, lax])|
-
-Returns values so that the construction
-@verbatim{
-for p, c in utf8.codes(s) do @rep{body} end
-}
-will iterate over all UTF-8 characters in string @id{s},
-with @id{p} being the position (in bytes) and @id{c} the code point
-of each character.
-It raises an error if it meets any invalid byte sequence.
-
-}
-
-@LibEntry{utf8.codepoint (s [, i [, j [, lax]]])|
-
-Returns the code points (as integers) from all characters in @id{s}
-that start between byte position @id{i} and @id{j} (both included).
-The default for @id{i} is 1 and for @id{j} is @id{i}.
-It raises an error if it meets any invalid byte sequence.
-
-}
-
-@LibEntry{utf8.len (s [, i [, j [, lax]]])|
-
-Returns the number of UTF-8 characters in string @id{s}
-that start between positions @id{i} and @id{j} (both inclusive).
-The default for @id{i} is @num{1} and for @id{j} is @num{-1}.
-If it finds any invalid byte sequence,
-returns @fail plus the position of the first invalid byte.
-
-}
-
-@LibEntry{utf8.offset (s, n [, i])|
-
-Returns the position of the @id{n}-th character of @id{s}
-(counting from byte position @id{i}) as two integers:
-The index (in bytes) where its encoding starts and the
-index (in bytes) where it ends.
-
-If the specified character is right after the end of @id{s},
-the function behaves as if there was a @Char{\0} there.
-If the specified character is neither in the subject
-nor right after its end,
-the function returns @fail.
-
-A negative @id{n} gets characters before position @id{i}.
-The default for @id{i} is 1 when @id{n} is non-negative
-and @T{#s + 1} otherwise,
-so that @T{utf8.offset(s,-n)} gets the offset of the
-@id{n}-th character from the end of the string.
-
-As a special case,
-when @id{n} is 0 the function returns the start and end
-of the encoding of the character that contains the
-@id{i}-th byte of @id{s}.
-
-This function assumes that @id{s} is a valid UTF-8 string.
-
-}
-
-}
-
-@sect2{tablib| @title{Table Manipulation}
-
-This library provides generic functions for table manipulation.
-It provides all its functions inside the table @defid{table}.
-
-Remember that, whenever an operation needs the length of a table,
-all caveats about the length operator apply @see{len-op}.
-All functions ignore non-numeric keys
-in the tables given as arguments.
-
-
-@LibEntry{table.concat (list [, sep [, i [, j]]])|
-
-Given a list where all elements are strings or numbers,
-returns the string @T{list[i]..sep..list[i+1] @Cdots sep..list[j]}.
-The default value for @id{sep} is the empty string,
-the default for @id{i} is 1,
-and the default for @id{j} is @T{#list}.
-If @id{i} is greater than @id{j}, returns the empty string.
-
-}
-
-@LibEntry{table.create (nseq [, nrec])|
-
-Creates a new empty table, preallocating memory.
-This preallocation may help performance and save memory
-when you know in advance how many elements the table will have.
-
-Parameter @id{nseq} is a hint for how many elements the table
-will have as a sequence.
-Optional parameter @id{nrec} is a hint for how many other elements
-the table will have; its default is zero.
-
-}
-
-@LibEntry{table.insert (list, [pos,] value)|
-
-Inserts element @id{value} at position @id{pos} in @id{list},
-shifting up the elements
-@T{list[pos],list[pos+1],@Cdots,list[#list]}.
-The default value for @id{pos} is @T{#list+1},
-so that a call @T{table.insert(t,x)} inserts @id{x} at the end
-of the list @id{t}.
-
-}
-
-@LibEntry{table.move (a1, f, e, t [,a2])|
-
-Moves elements from the table @id{a1} to the table @id{a2},
-performing the equivalent to the following
-multiple assignment:
-@T{a2[t],@Cdots = a1[f],@Cdots,a1[e]}.
-The default for @id{a2} is @id{a1}.
-The destination range can overlap with the source range.
-The number of elements to be moved must fit in a Lua integer.
-If @id{f} is larger than @id{e},
-nothing is moved.
-
-Returns the destination table @id{a2}.
-
-}
-
-@LibEntry{table.pack (@Cdots)|
-
-Returns a new table with all arguments stored into keys 1, 2, etc.
-and with a field @St{n} with the total number of arguments.
-Note that the resulting table may not be a sequence,
-if some arguments are @nil.
-
-}
-
-@LibEntry{table.remove (list [, pos])|
-
-Removes from @id{list} the element at position @id{pos},
-returning the value of the removed element.
-When @id{pos} is an integer between 1 and @T{#list},
-it shifts down the elements
-@T{list[pos+1],list[pos+2],@Cdots,list[#list]}
-and erases element @T{list[#list]};
-The index @id{pos} can also be 0 when @T{#list} is 0,
-or @T{#list + 1}.
-
-The default value for @id{pos} is @T{#list},
-so that a call @T{table.remove(l)} removes the last element
-of the list @id{l}.
-
-}
-
-@LibEntry{table.sort (list [, comp])|
-
-Sorts the list elements in a given order, @emph{in-place},
-from @T{list[1]} to @T{list[#list]}.
-If @id{comp} is given,
-then it must be a function that receives two list elements
-and returns true when the first element must come
-before the second in the final order,
-so that, after the sort,
-@T{i <= j} implies @T{not comp(list[j],list[i])}.
-If @id{comp} is not given,
-then the standard Lua operator @T{<} is used instead.
-
-The @id{comp} function must define a consistent order;
-more formally, the function must define a strict weak order.
-(A weak order is similar to a total order,
-but it can equate different elements for comparison purposes.)
-
-The sort algorithm is not stable:
-Different elements considered equal by the given order
-may have their relative positions changed by the sort.
-
-}
-
-@LibEntry{table.unpack (list [, i [, j]])|
-
-Returns the elements from the given list.
-This function is equivalent to
-@verbatim{
-return list[i], list[i+1], @Cdots, list[j]
-}
-By default, @id{i} @N{is 1} and @id{j} is @T{#list}.
-
-}
-
-}
-
-@sect2{mathlib| @title{Mathematical Functions}
-
-This library provides basic mathematical functions.
-It provides all its functions and constants inside the table @defid{math}.
-Functions with the annotation @St{integer/float} give
-integer results for integer arguments
-and float results for non-integer arguments.
-The rounding functions
-@Lid{math.ceil}, @Lid{math.floor}, and @Lid{math.modf}
-return an integer when the result fits in the range of an integer,
-or a float otherwise.
-
-@LibEntry{math.abs (x)|
-
-Returns the maximum value between @id{x} and @id{-x}. (integer/float)
-
-}
-
-@LibEntry{math.acos (x)|
-
-Returns the arc cosine of @id{x} (in radians).
-
-}
-
-@LibEntry{math.asin (x)|
-
-Returns the arc sine of @id{x} (in radians).
-
-}
-
-@LibEntry{math.atan (y [, x])|
-
-@index{atan} @index{atan2}
-Returns the arc tangent of @T{y/x} (in radians),
-using the signs of both arguments to find the
-quadrant of the result.
-It also handles correctly the case of @id{x} being zero.
-
-The default value for @id{x} is 1,
-so that the call @T{math.atan(y)}
-returns the arc tangent of @id{y}.
-
-}
-
-@LibEntry{math.ceil (x)|
-
-Returns the smallest integral value greater than or equal to @id{x}.
-
-}
-
-@LibEntry{math.cos (x)|
-
-Returns the cosine of @id{x} (assumed to be in radians).
-
-}
-
-@LibEntry{math.deg (x)|
-
-Converts the angle @id{x} from radians to degrees.
-
-}
-
-@LibEntry{math.exp (x)|
-
-Returns the value @M{e@sp{x}}
-(where @id{e} is the base of natural logarithms).
-
-}
-
-@LibEntry{math.floor (x)|
-
-Returns the largest integral value less than or equal to @id{x}.
-
-}
-
-@LibEntry{math.fmod (x, y)|
-
-Returns the remainder of the division of @id{x} by @id{y}
-that rounds the quotient towards zero. (integer/float)
-
-}
-
-@LibEntry{math.frexp (x)|
-
-Returns two numbers @id{m} and @id{e} such that @M{x = m2@sp{e}},
-where @id{e} is an integer.
-When @id{x} is zero, NaN, +inf, or -inf,
-@id{m} is equal to @id{x};
-otherwise, the absolute value of @id{m}
-is in the range @C{(} @M{[0.5, 1)} @C{]}.
-
-}
-
-@LibEntry{math.huge|
-
-The float value @idx{HUGE_VAL},
-a value greater than any other numeric value.
-
-}
-
-@LibEntry{math.ldexp (m, e)|
-
-Returns @M{m2@sp{e}}, where @id{e} is an integer.
-
-}
-
-@LibEntry{math.log (x [, base])|
-
-Returns the logarithm of @id{x} in the given base.
-The default for @id{base} is @M{e}
-(so that the function returns the natural logarithm of @id{x}).
-
-}
-
-@LibEntry{math.max (x, @Cdots)|
-
-Returns the argument with the maximum value,
-according to the Lua operator @T{<}.
-
-}
-
-@LibEntry{math.maxinteger|
-An integer with the maximum value for an integer.
-
-}
-
-@LibEntry{math.min (x, @Cdots)|
-
-Returns the argument with the minimum value,
-according to the Lua operator @T{<}.
-
-}
-
-@LibEntry{math.mininteger|
-An integer with the minimum value for an integer.
-
-}
-
-@LibEntry{math.modf (x)|
-
-Returns the integral part of @id{x} and the fractional part of @id{x}.
-Its second result is always a float.
-
-}
-
-@LibEntry{math.pi|
-
-The value of @M{@pi}.
-
-}
-
-@LibEntry{math.rad (x)|
-
-Converts the angle @id{x} from degrees to radians.
-
-}
-
-@LibEntry{math.random ([m [, n]])|
-
-When called without arguments,
-returns a pseudo-random float with uniform distribution
-in the range @C{(} @M{[0, 1)}. @C{]}
-When called with two integers @id{m} and @id{n},
-@id{math.random} returns a pseudo-random integer
-with uniform distribution in the range @M{[m, n]}.
-The call @T{math.random(n)}, for a positive @id{n},
-is equivalent to @T{math.random(1,n)}.
-The call @T{math.random(0)} produces an integer with
-all bits (pseudo)random.
-
-This function uses the @idx{xoshiro256**} algorithm to produce
-pseudo-random 64-bit integers,
-which are the results of calls with @N{argument 0}.
-Other results (ranges and floats)
-are unbiased extracted from these integers.
-
-Lua initializes its pseudo-random generator with the equivalent of
-a call to @Lid{math.randomseed} with no arguments,
-so that @id{math.random} should generate
-different sequences of results each time the program runs.
-
-}
-
-@LibEntry{math.randomseed ([x [, y]])|
-
-When called with at least one argument,
-the integer parameters @id{x} and @id{y} are
-joined into a @emphx{seed} that
-is used to reinitialize the pseudo-random generator;
-equal seeds produce equal sequences of numbers.
-The default for @id{y} is zero.
-
-When called with no arguments,
-Lua generates a seed with
-a weak attempt for randomness.
-
-This function returns the two seed components
-that were effectively used,
-so that setting them again repeats the sequence.
-
-To ensure a required level of randomness to the initial state
-(or contrarily, to have a deterministic sequence,
-for instance when debugging a program),
-you should call @Lid{math.randomseed} with explicit arguments.
-
-}
-
-@LibEntry{math.sin (x)|
-
-Returns the sine of @id{x} (assumed to be in radians).
-
-}
-
-@LibEntry{math.sqrt (x)|
-
-Returns the square root of @id{x}.
-(You can also use the expression @T{x^0.5} to compute this value.)
-
-}
-
-@LibEntry{math.tan (x)|
-
-Returns the tangent of @id{x} (assumed to be in radians).
-
-}
-
-@LibEntry{math.tointeger (x)|
-
-If the value @id{x} is convertible to an integer,
-returns that integer.
-Otherwise, returns @fail.
-
-}
-
-@LibEntry{math.type (x)|
-
-Returns @St{integer} if @id{x} is an integer,
-@St{float} if it is a float,
-or @fail if @id{x} is not a number.
-
-}
-
-@LibEntry{math.ult (m, n)|
-
-Returns a boolean,
-@true if and only if integer @id{m} is below integer @id{n} when
-they are compared as @x{unsigned integers}.
-
-}
-
-}
-
-@sect2{iolib| @title{Input and Output Facilities}
-
-The I/O library provides two different styles for file manipulation.
-The first one uses implicit file handles;
-that is, there are operations to set a default input file and a
-default output file,
-and all input/output operations are done over these default files.
-The second style uses explicit file handles.
-
-When using implicit file handles,
-all operations are supplied by table @defid{io}.
-When using explicit file handles,
-the operation @Lid{io.open} returns a file handle
-and then all operations are supplied as methods of the file handle.
-
-The metatable for file handles provides metamethods
-for @idx{__gc} and @idx{__close} that try
-to close the file when called.
-
-The table @id{io} also provides
-three predefined file handles with their usual meanings from C:
-@defid{io.stdin}, @defid{io.stdout}, and @defid{io.stderr}.
-The I/O library never closes these files.
-
-Unless otherwise stated,
-all I/O functions return @fail on failure,
-plus an error message as a second result and
-a system-dependent error code as a third result,
-and some non-false value on success.
-On non-POSIX systems,
-the computation of the error message and error code
-in case of errors
-may be not @x{thread safe},
-because they rely on the global C variable @id{errno}.
-
-@LibEntry{io.close ([file])|
-
-Equivalent to @T{file:close()}.
-Without a @id{file}, closes the default output file.
-
-}
-
-@LibEntry{io.flush ()|
-
-Equivalent to @T{io.output():flush()}.
-
-}
-
-@LibEntry{io.input ([file])|
-
-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 this file handle as the default input file.
-When called without arguments,
-it returns the current default input file.
-
-In case of errors this function raises the error,
-instead of returning an error code.
-
-}
-
-@LibEntry{io.lines ([filename, @Cdots])|
-
-Opens the given file name in read mode
-and returns an iterator function that
-works like @T{file:lines(@Cdots)} over the opened file.
-When the iterator function fails to read any value,
-it automatically closes the file.
-Besides the iterator function,
-@id{io.lines} returns three other values:
-two @nil values as placeholders,
-plus the created file handle.
-Therefore, when used in a generic @Rw{for} loop,
-the file is closed also if the loop is interrupted by an
-error or a @Rw{break}.
-
-The call @T{io.lines()} (with no file name) is equivalent
-to @T{io.input():lines("l")};
-that is, it iterates over the lines of the default input file.
-In this case, the iterator does not close the file when the loop ends.
-
-In case of errors opening the file,
-this function raises the error,
-instead of returning an error code.
-
-}
-
-@LibEntry{io.open (filename [, mode])|
-
-This function opens a file,
-in the mode specified in the string @id{mode}.
-In case of success,
-it returns a new file handle.
-
-The @id{mode} string can be any of the following:
-@description{
-@item{@St{r}| read mode (the default);}
-@item{@St{w}| write mode;}
-@item{@St{a}| append mode;}
-@item{@St{r+}| update mode, all previous data is preserved;}
-@item{@St{w+}| update mode, all previous data is erased;}
-@item{@St{a+}| append update mode, previous data is preserved,
- writing is only allowed at the end of file.}
-}
-The @id{mode} string can also have a @Char{b} at the end,
-which is needed in some systems to open the file in binary mode.
-
-}
-
-@LibEntry{io.output ([file])|
-
-Similar to @Lid{io.input}, but operates over the default output file.
-
-}
-
-@LibEntry{io.popen (prog [, mode])|
-
-This function is system dependent and is not available
-on all platforms.
-
-Starts the program @id{prog} in a separated process and returns
-a file handle that you can use to read data from this program
-(if @id{mode} is @T{"r"}, the default)
-or to write data to this program
-(if @id{mode} is @T{"w"}).
-
-}
-
-@LibEntry{io.read (@Cdots)|
-
-Equivalent to @T{io.input():read(@Cdots)}.
-
-}
-
-@LibEntry{io.tmpfile ()|
-
-In case of success,
-returns a handle for a temporary file.
-This file is opened in update mode
-and it is automatically removed when the program ends.
-
-}
-
-@LibEntry{io.type (obj)|
-
-Checks whether @id{obj} is a valid file handle.
-Returns the string @T{"file"} if @id{obj} is an open file handle,
-@T{"closed file"} if @id{obj} is a closed file handle,
-or @fail if @id{obj} is not a file handle.
-
-}
-
-@LibEntry{io.write (@Cdots)|
-
-Equivalent to @T{io.output():write(@Cdots)}.
-
-
-}
-
-@LibEntry{file:close ()|
-
-Closes @id{file}.
-Note that files are automatically closed when
-their handles are garbage collected,
-but that takes an unpredictable amount of time to happen.
-
-When closing a file handle created with @Lid{io.popen},
-@Lid{file:close} returns the same values
-returned by @Lid{os.execute}.
-
-}
-
-@LibEntry{file:flush ()|
-
-Saves any written data to @id{file}.
-
-}
-
-@LibEntry{file:lines (@Cdots)|
-
-Returns an iterator function that,
-each time it is called,
-reads the file according to the given formats.
-When no format is given,
-uses @St{l} as a default.
-As an example, the construction
-@verbatim{
-for c in file:lines(1) do @rep{body} end
-}
-will iterate over all characters of the file,
-starting at the current position.
-Unlike @Lid{io.lines}, this function does not close the file
-when the loop ends.
-
-}
-
-@LibEntry{file:read (@Cdots)|
-
-Reads the file @id{file},
-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 @fail if it cannot read data with the specified format.
-(In this latter case,
-the function does not read subsequent formats.)
-When called without arguments,
-it uses a default format that reads the next line
-(see below).
-
-The available formats are
-@description{
-
-@item{@St{n}|
-reads a numeral and returns it as a float or an integer,
-following the lexical conventions of Lua.
-(The numeral may have leading whitespaces and a sign.)
-This format always reads the longest input sequence that
-is a valid prefix for a numeral;
-if that prefix does not form a valid numeral
-(e.g., an empty string, @St{0x}, or @St{3.4e-})
-or it is too long (more than 200 characters),
-it is discarded and the format returns @fail.
-}
-
-@item{@St{a}|
-reads the whole file, starting at the current position.
-On end of file, it returns the empty string;
-this format never fails.
-}
-
-@item{@St{l}|
-reads the next line skipping the end of line,
-returning @fail on end of file.
-This is the default format.
-}
-
-@item{@St{L}|
-reads the next line keeping the end-of-line character (if present),
-returning @fail on end of file.
-}
-
-@item{@emph{number}|
-reads a string with up to this number of bytes,
-returning @fail on end of file.
-If @id{number} is zero,
-it reads nothing and returns an empty string,
-or @fail on end of file.
-}
-
-}
-The formats @St{l} and @St{L} should be used only for text files.
-
-}
-
-@LibEntry{file:seek ([whence [, offset]])|
-
-Sets and gets the file position,
-measured from the beginning of the file,
-to the position given by @id{offset} plus a base
-specified by the string @id{whence}, as follows:
-@description{
-@item{@St{set}| base is position 0 (beginning of the file);}
-@item{@St{cur}| base is current position;}
-@item{@St{end}| base is end of file;}
-}
-In case of success, @id{seek} returns the final file position,
-measured in bytes from the beginning of the file.
-If @id{seek} fails, it returns @fail,
-plus a string describing the error.
-
-The default value for @id{whence} is @T{"cur"},
-and for @id{offset} is 0.
-Therefore, the call @T{file:seek()} returns the current
-file position, without changing it;
-the call @T{file:seek("set")} sets the position to the
-beginning of the file (and returns 0);
-and the call @T{file:seek("end")} sets the position to the
-end of the file, and returns its size.
-
-}
-
-@LibEntry{file:setvbuf (mode [, size])|
-
-Sets the buffering mode for a file.
-There are three available modes:
-@description{
-@item{@St{no}| no buffering.}
-@item{@St{full}| full buffering.}
-@item{@St{line}| line buffering.}
-}
-
-For the last two cases,
-@id{size} is a hint for the size of the buffer, in bytes.
-The default is an appropriate size.
-
-The specific behavior of each mode is non portable;
-check the underlying @ANSI{setvbuf} in your platform for
-more details.
-
-}
-
-@LibEntry{file:write (@Cdots)|
-
-Writes the value of each of its arguments to @id{file}.
-The arguments must be strings or numbers.
-
-In case of success, this function returns @id{file}.
-Otherwise, it returns four values:
-@fail, the error message, the error code,
-and the number of bytes it was able to write.
-
-}
-
-}
-
-@sect2{oslib| @title{Operating System Facilities}
-
-This library is implemented through table @defid{os}.
-
-
-@LibEntry{os.clock ()|
-
-Returns an approximation of the amount in seconds of CPU time
-used by the program,
-as returned by the underlying @ANSI{clock}.
-
-}
-
-@LibEntry{os.date ([format [, time]])|
-
-Returns a string or a table containing date and time,
-formatted according to the given string @id{format}.
-
-If the @id{time} argument is present,
-this is the time to be formatted
-(see the @Lid{os.time} function for a description of this value).
-Otherwise, @id{date} formats the current time.
-
-If @id{format} starts with @Char{!},
-then the date is formatted in Coordinated Universal Time.
-After this optional character,
-if @id{format} is the string @St{*t},
-then @id{date} returns a table with the following fields:
-@id{year}, @id{month} (1@En{}12), @id{day} (1@En{}31),
-@id{hour} (0@En{}23), @id{min} (0@En{}59),
-@id{sec} (0@En{}61, due to leap seconds),
-@id{wday} (weekday, 1@En{}7, Sunday @N{is 1}),
-@id{yday} (day of the year, 1@En{}366),
-and @id{isdst} (daylight saving flag, a boolean).
-This last field may be absent
-if the information is not available.
-
-If @id{format} is not @St{*t},
-then @id{date} returns the date as a string,
-formatted according to the same rules as the @ANSI{strftime}.
-
-If @id{format} is absent, it defaults to @St{%c},
-which gives a human-readable date and time representation
-using the current locale.
-
-On non-POSIX systems,
-this function may be not @x{thread safe}
-because of its reliance on @CId{gmtime} and @CId{localtime}.
-
-}
-
-@LibEntry{os.difftime (t2, t1)|
-
-Returns the difference, in seconds,
-from time @id{t1} to time @id{t2}
-(where the times are values returned by @Lid{os.time}).
-In @x{POSIX}, @x{Windows}, and some other systems,
-this value is exactly @id{t2}@M{-}@id{t1}.
-
-}
-
-@LibEntry{os.execute ([command])|
-
-This function is equivalent to the @ANSI{system}.
-It passes @id{command} to be executed by an operating system shell.
-Its first result is @true
-if the command terminated successfully,
-or @fail otherwise.
-After this first result
-the function returns a string plus a number,
-as follows:
-@description{
-
-@item{@St{exit}|
-the command terminated normally;
-the following number is the exit status of the command.
-}
-
-@item{@St{signal}|
-the command was terminated by a signal;
-the following number is the signal that terminated the command.
-}
-
-}
-
-When called without a @id{command},
-@id{os.execute} returns a boolean that is true if a shell is available.
-
-}
-
-@LibEntry{os.exit ([code [, close]])|
-
-Calls the @ANSI{exit} to terminate the host program.
-If @id{code} is @true,
-the returned status is @idx{EXIT_SUCCESS};
-if @id{code} is @false,
-the returned status is @idx{EXIT_FAILURE};
-if @id{code} is a number,
-the returned status is this number.
-The default value for @id{code} is @true.
-
-If the optional second argument @id{close} is true,
-the function closes the Lua state before exiting @seeF{lua_close}.
-
-}
-
-@LibEntry{os.getenv (varname)|
-
-Returns the value of the process environment variable @id{varname}
-or @fail if the variable is not defined.
-
-}
-
-@LibEntry{os.remove (filename)|
-
-Deletes the file (or empty directory, on @x{POSIX} systems)
-with the given name.
-If this function fails, it returns @fail
-plus a string describing the error and the error code.
-Otherwise, it returns true.
-
-}
-
-@LibEntry{os.rename (oldname, newname)|
-
-Renames the file or directory named @id{oldname} to @id{newname}.
-If this function fails, it returns @fail,
-plus a string describing the error and the error code.
-Otherwise, it returns true.
-
-}
-
-@LibEntry{os.setlocale (locale [, category])|
-
-Sets the current locale of the program.
-@id{locale} is a system-dependent string specifying a locale;
-@id{category} is an optional string describing which category to change:
-@T{"all"}, @T{"collate"}, @T{"ctype"},
-@T{"monetary"}, @T{"numeric"}, or @T{"time"};
-the default category is @T{"all"}.
-The function returns the name of the new locale,
-or @fail if the request cannot be honored.
-
-If @id{locale} is the empty string,
-the current locale is set to an implementation-defined native locale.
-If @id{locale} is the string @St{C},
-the current locale is set to the standard C locale.
-
-When called with @nil as the first argument,
-this function only returns the name of the current locale
-for the given category.
-
-This function may be not @x{thread safe}
-because of its reliance on @CId{setlocale}.
-
-}
-
-@LibEntry{os.time ([table])|
-
-Returns the current local time when called without arguments,
-or a time representing the local date and time specified by the given table.
-This table must have fields @id{year}, @id{month}, and @id{day},
-and may have fields
-@id{hour} (default is 12),
-@id{min} (default is 0),
-@id{sec} (default is 0),
-and @id{isdst} (default is @nil).
-Other fields are ignored.
-For a description of these fields, see the @Lid{os.date} function.
-
-When the function is called,
-the values in these fields do not need to be inside their valid ranges.
-For instance, if @id{sec} is -10,
-it means 10 seconds before the time specified by the other fields;
-if @id{hour} is 1000,
-it means 1000 hours after the time specified by the other fields.
-
-The returned value is a number, whose meaning depends on your system.
-In @x{POSIX}, @x{Windows}, and some other systems,
-this number counts the number
-of seconds since some given start time (the @Q{epoch}).
-In other systems, the meaning is not specified,
-and the number returned by @id{time} can be used only as an argument to
-@Lid{os.date} and @Lid{os.difftime}.
-
-When called with a table,
-@id{os.time} also normalizes all the fields
-documented in the @Lid{os.date} function,
-so that they represent the same time as before the call
-but with values inside their valid ranges.
-
-}
-
-@LibEntry{os.tmpname ()|
-
-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 explicitly removed when no longer needed.
-
-In @x{POSIX} systems,
-this function also creates a file with that name,
-to avoid security risks.
-(Someone else might create the file with wrong permissions
-in the time between getting the name and creating the file.)
-You still have to open the file to use it
-and to remove it (even if you do not use it).
-
-When possible,
-you may prefer to use @Lid{io.tmpfile},
-which automatically removes the file when the program ends.
-
-}
-
-}
-
-@sect2{debuglib| @title{The Debug Library}
-
-This library provides
-the functionality of the @link{debugI|debug interface} to Lua programs.
-You should exert care when using this library.
-Several of its functions
-violate basic assumptions about Lua code
-(e.g., that variables local to a function
-cannot be accessed from outside;
-that userdata metatables cannot be changed by Lua code;
-that Lua programs do not crash)
-and therefore can compromise otherwise secure code.
-Moreover, some functions in this library may be slow.
-
-All functions in this library are provided
-inside the @defid{debug} table.
-All functions that operate over a thread
-have an optional first argument which is the
-thread to operate over.
-The default is always the current thread.
-
-
-@LibEntry{debug.debug ()|
-
-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 @id{cont} finishes this function,
-so that the caller continues its execution.
-
-Note that commands for @id{debug.debug} are not lexically nested
-within any function and so have no direct access to local variables.
-
-}
-
-@LibEntry{debug.gethook ([thread])|
-
-Returns the current hook settings of the thread, as three values:
-the current hook function, the current hook mask,
-and the current hook count,
-as set by the @Lid{debug.sethook} function.
-
-Returns @fail if there is no active hook.
-
-}
-
-@LibEntry{debug.getinfo ([thread,] f [, what])|
-
-Returns a table with information about a function.
-You can give the function directly
-or you can give a number as the value of @id{f},
-which means the function running at level @id{f} of the call stack
-of the given thread:
-@N{level 0} is the current function (@id{getinfo} itself);
-@N{level 1} is the function that called @id{getinfo}
-(except for tail calls, which do not count in the stack);
-and so on.
-If @id{f} is a number greater than the number of active functions,
-then @id{getinfo} returns @fail.
-
-The returned table can contain all the fields returned by @Lid{lua_getinfo},
-with the string @id{what} describing which fields to fill in.
-The default for @id{what} is to get all information available,
-except the table of valid lines.
-The option @Char{f}
-adds a field named @id{func} with the function itself.
-The option @Char{L} adds a field named @id{activelines}
-with the table of valid lines,
-provided the function is a Lua function.
-If the function has no debug information,
-the table is empty.
-
-For instance, the expression @T{debug.getinfo(1,"n").name} returns
-a name for the current function,
-if a reasonable name can be found,
-and the expression @T{debug.getinfo(print)}
-returns a table with all available information
-about the @Lid{print} function.
-
-}
-
-@LibEntry{debug.getlocal ([thread,] f, local)|
-
-This function returns the name and the value of the local variable
-with index @id{local} of the function at level @id{f} of the stack.
-This function accesses not only explicit local variables,
-but also parameters and temporary values.
-
-The first parameter or local variable has @N{index 1}, and so on,
-following the order that they are declared in the code,
-counting only the variables that are active
-in the current scope of the function.
-Compile-time constants may not appear in this listing,
-if they were optimized away by the compiler.
-Negative indices refer to vararg arguments;
-@num{-1} is the first vararg argument.
-These negative indices are only available when the vararg table
-has been optimized away;
-otherwise, the vararg arguments are available in the vararg table.
-
-The function returns @fail
-if there is no variable with the given index,
-and raises an error when called with a level out of range.
-(You can call @Lid{debug.getinfo} to check whether the level is valid.)
-
-Variable names starting with @Char{(} (open parenthesis) @C{)}
-represent variables with no known names
-(internal variables such as loop control variables,
-and variables from chunks saved without debug information).
-
-The parameter @id{f} may also be a function.
-In that case, @id{getlocal} returns only the name of function parameters.
-
-}
-
-@LibEntry{debug.getmetatable (value)|
-
-Returns the metatable of the given @id{value}
-or @nil if it does not have a metatable.
-
-}
-
-@LibEntry{debug.getregistry ()|
-
-Returns the registry table @see{registry}.
-
-}
-
-@LibEntry{debug.getupvalue (f, up)|
-
-This function returns the name and the value of the upvalue
-with index @id{up} of the function @id{f}.
-The function returns @fail
-if there is no upvalue with the given index.
-
-(For Lua functions,
-upvalues are the external local variables that the function uses,
-and that are consequently included in its closure.)
-
-For @N{C functions}, this function uses the empty string @T{""}
-as a name for all upvalues.
-
-Variable name @Char{?} (interrogation mark)
-represents variables with no known names
-(variables from chunks saved without debug information).
-
-}
-
-@LibEntry{debug.getuservalue (u, n)|
-
-Returns the @id{n}-th user value associated
-to the userdata @id{u} plus a boolean,
-@false if the userdata does not have that value.
-
-}
-
-@LibEntry{debug.sethook ([thread,] hook, mask [, count])|
-
-Sets the given function as the debug hook.
-The string @id{mask} and the number @id{count} describe
-when the hook will be called.
-The string mask may have any combination of the following characters,
-with the given meaning:
-@description{
-@item{@Char{c}| the hook is called every time Lua calls a function;}
-@item{@Char{r}| the hook is called every time Lua returns from a function;}
-@item{@Char{l}| the hook is called every time Lua enters a new line of code.}
-}
-Moreover,
-with a @id{count} different from zero,
-the hook is called also after every @id{count} instructions.
-
-When called without arguments,
-@Lid{debug.sethook} turns off the hook.
-
-When the hook is called, its first parameter is a string
-describing the event that has triggered its call:
-@T{"call"}, @T{"tail call"}, @T{"return"},
-@T{"line"}, and @T{"count"}.
-For line events,
-the hook also gets the new line number as its second parameter.
-Inside a hook,
-you can call @id{getinfo} with @N{level 2} to get more information about
-the running function.
-(@N{Level 0} is the @id{getinfo} function,
-and @N{level 1} is the hook function.)
-
-}
-
-@LibEntry{debug.setlocal ([thread,] level, local, value)|
-
-This function assigns the value @id{value} to the local variable
-with index @id{local} of the function at level @id{level} of the stack.
-The function returns @fail if there is no local
-variable with the given index,
-and raises an error when called with a @id{level} out of range.
-(You can call @id{getinfo} to check whether the level is valid.)
-Otherwise, it returns the name of the local variable.
-
-See @Lid{debug.getlocal} for more information about
-variable indices and names.
-
-}
-
-@LibEntry{debug.setmetatable (value, table)|
-
-Sets the metatable for the given @id{value} to the given @id{table}
-(which can be @nil).
-Returns @id{value}.
-
-}
-
-@LibEntry{debug.setupvalue (f, up, value)|
-
-This function assigns the value @id{value} to the upvalue
-with index @id{up} of the function @id{f}.
-The function returns @fail if there is no upvalue
-with the given index.
-Otherwise, it returns the name of the upvalue.
-
-See @Lid{debug.getupvalue} for more information about upvalues.
-
-}
-
-@LibEntry{debug.setuservalue (udata, value, n)|
-
-Sets the given @id{value} as
-the @id{n}-th user value associated to the given @id{udata}.
-@id{udata} must be a full userdata.
-
-Returns @id{udata},
-or @fail if the userdata does not have that value.
-
-}
-
-@LibEntry{debug.traceback ([thread,] [message [, level]])|
-
-If @id{message} is present but is neither a string nor @nil,
-this function returns @id{message} without further processing.
-Otherwise,
-it returns a string with a traceback of the call stack.
-The optional @id{message} string is appended
-at the beginning of the traceback.
-An optional @id{level} number tells at which level
-to start the traceback
-(default is 1, the function calling @id{traceback}).
-
-}
-
-@LibEntry{debug.upvalueid (f, n)|
-
-Returns a unique identifier (as a light userdata)
-for the upvalue numbered @id{n}
-from the given function.
-
-These unique identifiers allow a program to check whether different
-closures share upvalues.
-Lua closures that share an upvalue
-(that is, that access a same external local variable)
-will return identical ids for those upvalue indices.
-
-}
-
-@LibEntry{debug.upvaluejoin (f1, n1, f2, n2)|
-
-Make the @id{n1}-th upvalue of the Lua closure @id{f1}
-refer to the @id{n2}-th upvalue of the Lua closure @id{f2}.
-
-}
-
-}
-
-}
-
-
-@C{-------------------------------------------------------------------------}
-@sect1{lua-sa| @title{Lua Standalone}
-
-Although Lua has been designed as an extension language,
-to be embedded in a host @N{C program},
-it is also frequently used as a standalone language.
-An interpreter for Lua as a standalone language,
-called simply @id{lua},
-is provided with the standard distribution.
-The @x{standalone interpreter} includes
-all standard libraries.
-Its usage is:
-@verbatim{
-lua [options] [script [args]]
-}
-The options are:
-@description{
-@item{@T{-e @rep{stat}}| execute string @rep{stat};}
-@item{@T{-i}| enter interactive mode after running @rep{script};}
-@item{@T{-l @rep{mod}}| @Q{require} @rep{mod} and assign the
- result to global @rep{mod};}
-@item{@T{-l @rep{g=mod}}| @Q{require} @rep{mod} and assign the
- result to global @rep{g};}
-@item{@T{-v}| print version information;}
-@item{@T{-E}| ignore environment variables;}
-@item{@T{-W}| turn warnings on;}
-@item{@T{--}| stop handling options;}
-@item{@T{-}| execute @id{stdin} as a file and stop handling options.}
-}
-
-After handling its options, @id{lua} runs the given @emph{script}.
-When called without arguments,
-@id{lua} behaves as @T{lua -v -i}
-when the standard input (@id{stdin}) is a terminal,
-and as @T{lua -} otherwise.
-
-When called without the option @T{-E},
-the interpreter checks for an environment variable @defid{LUA_INIT_5_5}
-(or @defid{LUA_INIT} if the versioned name is not defined)
-before running any argument.
-If the variable content has the format @T{@At@rep{filename}},
-then @id{lua} executes the file.
-Otherwise, @id{lua} executes the string itself.
-
-When called with the option @T{-E},
-Lua does not consult any environment variables.
-In particular,
-the values of @Lid{package.path} and @Lid{package.cpath}
-are set with the default paths defined in @id{luaconf.h}.
-To signal to the libraries that this option is on,
-the stand-alone interpreter sets the field
-@idx{"LUA_NOENV"} in the registry to a true value.
-Other libraries may consult this field for the same purpose.
-
-The options @T{-e}, @T{-l}, and @T{-W} are handled in
-the order they appear.
-For instance, an invocation like
-@verbatim{
-$ lua -e 'a=1' -llib1 script.lua
-}
-will first set @id{a} to 1, then require the library @id{lib1},
-and finally run the file @id{script.lua} with no arguments.
-(Here @T{$} is the shell prompt. Your prompt may be different.)
-
-Before running any code,
-@id{lua} collects all command-line arguments
-in a global table called @id{arg}.
-The script name goes to 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 its options)
-go to negative indices.
-For instance, in the call
-@verbatim{
-$ lua -la b.lua t1 t2
-}
-the table is like this:
-@verbatim{
-arg = { [-2] = "lua", [-1] = "-la",
- [0] = "b.lua",
- [1] = "t1", [2] = "t2" }
-}
-If there is no script in the call,
-the interpreter name goes to index 0,
-followed by the other arguments.
-For instance, the call
-@verbatim{
-$ lua -e "print(arg[1])"
-}
-will print @St{-e}.
-If there is a script,
-the script is called with arguments
-@T{arg[1]}, @Cdots, @T{arg[#arg]}.
-Like all chunks in Lua,
-the script is compiled as a variadic function.
-
-In interactive mode,
-Lua repeatedly prompts and waits for a line.
-After reading a line,
-Lua first tries to interpret the line as an expression.
-If it succeeds, it prints its value.
-Otherwise, it interprets the line as a chunk.
-If you write an incomplete chunk,
-the interpreter waits for its completion
-by issuing a different prompt.
-
-Note that, as each complete line is read as a new chunk,
-local variables do not outlive lines.
-To steer clear of confusion,
-the interpreter gives a warning if a line starts with the
-reserved word @Rw{local}:
-@verbatim{
-> x = 20 -- global 'x'
-> local x = 10; print(x)
- --> warning: locals do not survive across lines in interactive mode
- --> 10
-> print(x) -- back to global 'x'
- --> 20
-> do -- incomplete chunk
->> local x = 10; print(x) -- '>>' prompts for line completion
->> print(x)
->> end -- chunk completed
- --> 10
- --> 10
-}
-
-If the global variable @defid{_PROMPT} contains a string,
-then its value is used as the prompt.
-Similarly, if the global variable @defid{_PROMPT2} contains a string,
-its value is used as the secondary prompt
-(issued during incomplete statements).
-
-In case of unprotected errors in the script,
-the interpreter reports the error to the standard error stream.
-If the error object is not a string but
-has a metamethod @idx{__tostring},
-the interpreter calls this metamethod to produce the final message.
-Otherwise, the interpreter converts the error object to a string
-and adds a stack traceback to it.
-When warnings are on,
-they are simply printed in the standard error output.
-
-When finishing normally,
-the interpreter closes its main Lua state
-@seeF{lua_close}.
-The script can avoid this step by
-calling @Lid{os.exit} to terminate.
-
-To allow the use of Lua as a
-script interpreter in Unix systems,
-Lua skips the first line of a file chunk if it starts with @T{#}.
-Therefore, Lua scripts can be made into executable programs
-by using @T{chmod +x} and @N{the @T{#!}} form,
-as in
-@verbatim{
-#!/usr/local/bin/lua
-}
-Of course,
-the location of the Lua interpreter may be different in your machine.
-If @id{lua} is in your @id{PATH},
-then
-@verbatim{
-#!/usr/bin/env lua
-}
-is a more portable solution.
-
-}
-
-
-@sect1{incompat| @title{Incompatibilities with the Previous Version}
-
-@simplesect{
-
-Here we list the incompatibilities that you may find when moving a program
-from @N{Lua 5.4} to @N{Lua 5.5}.
-
-You can avoid some incompatibilities by compiling Lua with
-appropriate options (see file @id{luaconf.h}).
-However,
-all these compatibility options will be removed in the future.
-More often than not,
-compatibility issues arise when these compatibility options
-are removed.
-So, whenever you have the chance,
-you should try to test your code with a version of Lua compiled
-with all compatibility options turned off.
-That will ease transitions to newer versions of Lua.
-
-Lua versions can always change the C API in ways that
-do not imply source-code changes in a program,
-such as the numeric values for constants
-or the implementation of functions as macros.
-Therefore,
-you should never assume that binaries are compatible between
-different Lua versions.
-Always recompile clients of the Lua API when
-using a new version.
-
-Similarly, Lua versions can always change the internal representation
-of precompiled chunks;
-precompiled chunks are not compatible between different Lua versions.
-
-The standard paths in the official distribution may
-change between versions.
-
-}
-
-@sect2{@title{Incompatibilities in the Language}
-@itemize{
-
-@item{
-The word @Rw{global} is a reserved word.
-Do not use it as a regular name.
-
-The compilation option @id{LUA_COMPAT_GLOBAL} (see @id{luaconf.h})
-makes @id{global} a regular word.
-}
-
-@item{
-The control variable in @Rw{for} loops is read only.
-If you need to change it,
-declare a local variable with the same name in the loop body.
-
-The compilation option @id{LUA_COMPAT_LOOPVAR} (see @id{luaconf.h})
-makes these variables regular (writable).
-}
-
-@item{
-A chain of @id{__call} metamethods can have at most 15 objects.
-}
-
-@item{
-In an error, a @nil as the error object is replaced by a
-string message.
-}
-
-}
-
-}
-
-@sect2{@title{Incompatibilities in the Libraries}
-@itemize{
-
-@item{
-Parameters for the garbage collection are not set
-with the options @St{incremental} and @St{generational};
-instead, there is a new option @St{param} to that end.
-Moreover, there were some changes in the parameters themselves.
-}
-
-}
-
-}
-
-@sect2{@title{Incompatibilities in the API}
-
-@itemize{
-
-@item{
-In @Lid{lua_call} and related functions,
-the maximum value for the number of required results
-(@id{nresults}) is 250.
-If you really need a larger value,
-use @Lid{LUA_MULTRET} and then adjust the stack size.
-Previously, this limit was unspecified.
-}
-
-@item{
-@Lid{lua_newstate} has a third parameter,
-a seed for the hashing of strings.
-}
-
-@item{
-The function @id{lua_resetthread} is deprecated;
-it is equivalent to @Lid{lua_closethread} with
-@id{from} being @id{NULL}.
-}
-
-@item{
-The function @id{lua_setcstacklimit} is deprecated.
-Calls to it can simply be removed.
-}
-
-@item{
-The function @Lid{lua_dump} changed the way it keeps the stack
-through the calls to the writer function.
-(That was not specified in previous versions.)
-Also, it calls the writer function one extra time,
-to signal the end of the dump.
-}
-
-@item{
-Parameters for the garbage collection are not set
-with the options @Lid{LUA_GCINC} and @Lid{LUA_GCGEN};
-instead, there is a new option @Lid{LUA_GCPARAM} to that end.
-Moreover, there were some changes in the parameters themselves.
-}
-
-@item{
-The function @Lid{lua_pushvfstring} now reports errors,
-instead of raising them.
-}
-
-}
-
-}
-
-}
-
-
-@C{[===============================================================}
-
-@sect1{BNF| @title{The Complete Syntax of Lua}
-
-Here is the complete syntax of Lua in extended BNF.
-As usual in extended BNF,
-@bnfNter{{A}} means 0 or more @bnfNter{A}s,
-and @bnfNter{[A]} means an optional @bnfNter{A}.
-(For operator precedences, see @See{prec};
-for a description of the terminals
-@bnfNter{Name}, @bnfNter{Numeral},
-and @bnfNter{LiteralString}, see @See{lexical}.)
-@index{grammar}
-
-@Produc{
-
-@producname{chunk}@producbody{block}
-
-@producname{block}@producbody{@bnfrep{stat} @bnfopt{retstat}}
-
-@producname{stat}@producbody{
- @bnfter{;}
-@OrNL varlist @bnfter{=} explist
-@OrNL functioncall
-@OrNL label
-@OrNL @Rw{break}
-@OrNL @Rw{goto} Name
-@OrNL @Rw{do} block @Rw{end}
-@OrNL @Rw{while} exp @Rw{do} block @Rw{end}
-@OrNL @Rw{repeat} block @Rw{until} exp
-@OrNL @Rw{if} exp @Rw{then} block
- @bnfrep{@Rw{elseif} exp @Rw{then} block}
- @bnfopt{@Rw{else} block} @Rw{end}
-@OrNL @Rw{for} @bnfNter{Name} @bnfter{=} exp @bnfter{,} exp @bnfopt{@bnfter{,} exp}
- @Rw{do} block @Rw{end}
-@OrNL @Rw{for} namelist @Rw{in} explist @Rw{do} block @Rw{end}
-@OrNL @Rw{function} funcname funcbody
-@OrNL @Rw{local} @Rw{function} @bnfNter{Name} funcbody
-@OrNL @Rw{global} @Rw{function} @bnfNter{Name} funcbody
-@OrNL @Rw{local} attnamelist @bnfopt{@bnfter{=} explist}
-@OrNL @Rw{global} attnamelist @bnfopt{@bnfter{=} explist}
-@OrNL @Rw{global} @bnfopt{attrib} @bnfter{*}
-}
-
-@producname{attnamelist}@producbody{
- @bnfopt{attrib} @bnfNter{Name} @bnfopt{attrib}
- @bnfrep{@bnfter{,} @bnfNter{Name} @bnfopt{attrib}}}
-
-@producname{attrib}@producbody{@bnfter{<} @bnfNter{Name} @bnfter{>}}
-
-@producname{retstat}@producbody{@Rw{return}
- @bnfopt{explist} @bnfopt{@bnfter{;}}}
-
-@producname{label}@producbody{@bnfter{::} Name @bnfter{::}}
-
-@producname{funcname}@producbody{@bnfNter{Name} @bnfrep{@bnfter{.} @bnfNter{Name}}
- @bnfopt{@bnfter{:} @bnfNter{Name}}}
-
-@producname{varlist}@producbody{var @bnfrep{@bnfter{,} var}}
-
-@producname{var}@producbody{
- @bnfNter{Name}
-@Or prefixexp @bnfter{[} exp @bnfter{]}
-@Or prefixexp @bnfter{.} @bnfNter{Name}
-}
-
-@producname{namelist}@producbody{@bnfNter{Name} @bnfrep{@bnfter{,} @bnfNter{Name}}}
-
-
-@producname{explist}@producbody{exp @bnfrep{@bnfter{,} exp}}
-
-@producname{exp}@producbody{
- @Rw{nil}
-@Or @Rw{false}
-@Or @Rw{true}
-@Or @bnfNter{Numeral}
-@Or @bnfNter{LiteralString}
-@Or @bnfter{...}
-@Or functiondef
-@OrNL prefixexp
-@Or tableconstructor
-@Or exp binop exp
-@Or unop exp
-}
-
-@producname{prefixexp}@producbody{var @Or functioncall @Or @bnfter{(} exp @bnfter{)}}
-
-@producname{functioncall}@producbody{
- prefixexp args
-@Or prefixexp @bnfter{:} @bnfNter{Name} args
-}
-
-@producname{args}@producbody{
- @bnfter{(} @bnfopt{explist} @bnfter{)}
-@Or tableconstructor
-@Or @bnfNter{LiteralString}
-}
-
-@producname{functiondef}@producbody{@Rw{function} funcbody}
-
-@producname{funcbody}@producbody{@bnfter{(} @bnfopt{parlist} @bnfter{)} block @Rw{end}}
-
-@producname{parlist}@producbody{namelist @bnfopt{@bnfter{,} varargparam} @Or
- varargparam}
-
-@producname{varargparam}@producbody{@bnfter{...} @bnfopt{@bnfNter{Name}}}
-
-@producname{tableconstructor}@producbody{@bnfter{@Open} @bnfopt{fieldlist} @bnfter{@Close}}
-
-@producname{fieldlist}@producbody{field @bnfrep{fieldsep field} @bnfopt{fieldsep}}
-
-@producname{field}@producbody{@bnfter{[} exp @bnfter{]} @bnfter{=} exp @Or @bnfNter{Name} @bnfter{=} exp @Or exp}
-
-@producname{fieldsep}@producbody{@bnfter{,} @Or @bnfter{;}}
-
-@producname{binop}@producbody{
- @bnfter{+} @Or @bnfter{-} @Or @bnfter{*} @Or @bnfter{/} @Or @bnfter{//}
- @Or @bnfter{^} @Or @bnfter{%}
- @OrNL
- @bnfter{&} @Or @bnfter{~} @Or @bnfter{|} @Or @bnfter{>>} @Or @bnfter{<<}
- @Or @bnfter{..}
- @OrNL
- @bnfter{<} @Or @bnfter{<=} @Or @bnfter{>} @Or @bnfter{>=}
- @Or @bnfter{==} @Or @bnfter{~=}
- @OrNL
- @Rw{and} @Or @Rw{or}}
-
-@producname{unop}@producbody{@bnfter{-} @Or @Rw{not} @Or @bnfter{#} @Or
- @bnfter{~}}
-
-}
-
-}
-
-@C{]===============================================================}
-
-}
-@C{)]-------------------------------------------------------------------------}
diff --git a/onelua.c b/onelua.c
deleted file mode 100644
index e717121391..0000000000
--- a/onelua.c
+++ /dev/null
@@ -1,136 +0,0 @@
-/*
-** Lua core, libraries, and interpreter in a single file.
-** Compiling just this file generates a complete Lua stand-alone
-** program:
-**
-** $ gcc -O2 -std=c99 -o lua onelua.c -lm
-**
-** or (for C89)
-**
-** $ gcc -O2 -std=c89 -DLUA_USE_C89 -o lua onelua.c -lm
-**
-** or (for Linux)
-**
-** gcc -O2 -o lua -DLUA_USE_LINUX -Wl,-E onelua.c -lm -ldl
-**
-*/
-
-/* default is to build the full interpreter */
-#ifndef MAKE_LIB
-#ifndef MAKE_LUAC
-#ifndef MAKE_LUA
-#define MAKE_LUA
-#endif
-#endif
-#endif
-
-
-/*
-** Choose suitable platform-specific features. Default is no
-** platform-specific features. Some of these options may need extra
-** libraries such as -ldl -lreadline -lncurses
-*/
-#if 0
-#define LUA_USE_LINUX
-#define LUA_USE_MACOSX
-#define LUA_USE_POSIX
-#endif
-
-
-/*
-** Other specific features
-*/
-#if 0
-#define LUA_32BITS
-#define LUA_USE_C89
-#endif
-
-
-/* no need to change anything below this line ----------------------------- */
-
-#include "lprefix.h"
-
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-
-/* setup for luaconf.h */
-#define LUA_CORE
-#define LUA_LIB
-
-#include "luaconf.h"
-
-/* do not export internal symbols */
-#undef LUAI_FUNC
-#undef LUAI_DDEC
-#undef LUAI_DDEF
-#define LUAI_FUNC static
-#define LUAI_DDEC(def) /* empty */
-#define LUAI_DDEF static
-
-/* core -- used by all */
-#include "lzio.c"
-#include "lctype.c"
-#include "lopcodes.c"
-#include "lmem.c"
-#include "lundump.c"
-#include "ldump.c"
-#include "lstate.c"
-#include "lgc.c"
-#include "llex.c"
-#include "lcode.c"
-#include "lparser.c"
-#include "ldebug.c"
-#include "lfunc.c"
-#include "lobject.c"
-#include "ltm.c"
-#include "lstring.c"
-#include "ltable.c"
-#include "ldo.c"
-#include "lvm.c"
-#include "lapi.c"
-
-/* auxiliary library -- used by all */
-#include "lauxlib.c"
-
-/* standard library -- not used by luac */
-#ifndef MAKE_LUAC
-#include "lbaselib.c"
-#include "lcorolib.c"
-#include "ldblib.c"
-#include "liolib.c"
-#include "lmathlib.c"
-#include "loadlib.c"
-#include "loslib.c"
-#include "lstrlib.c"
-#include "ltablib.c"
-#include "lutf8lib.c"
-#include "linit.c"
-#endif
-
-/* test library -- used only for internal development */
-#if defined(LUA_DEBUG)
-#include "ltests.c"
-#endif
-
-/* lua */
-#ifdef MAKE_LUA
-#include "lua.c"
-#endif
-
-/* luac */
-#ifdef MAKE_LUAC
-#include "luac.c"
-#endif
diff --git a/src/Makefile b/src/Makefile
new file mode 100644
index 0000000000..2e7a4120ce
--- /dev/null
+++ b/src/Makefile
@@ -0,0 +1,197 @@
+# Makefile for building Lua
+# See ../doc/readme.html for installation and customization instructions.
+
+# == CHANGE THE SETTINGS BELOW TO SUIT YOUR ENVIRONMENT =======================
+
+# Your platform. See PLATS for possible values.
+PLAT= none
+
+CC= gcc -std=gnu99
+CFLAGS= -O2 -Wall -Wextra -DLUA_COMPAT_5_2 $(SYSCFLAGS) $(MYCFLAGS)
+LDFLAGS= $(SYSLDFLAGS) $(MYLDFLAGS)
+LIBS= -lm $(SYSLIBS) $(MYLIBS)
+
+AR= ar rcu
+RANLIB= ranlib
+RM= rm -f
+
+SYSCFLAGS=
+SYSLDFLAGS=
+SYSLIBS=
+
+MYCFLAGS=
+MYLDFLAGS=
+MYLIBS=
+MYOBJS=
+
+# == END OF USER SETTINGS -- NO NEED TO CHANGE ANYTHING BELOW THIS LINE =======
+
+PLATS= aix bsd c89 freebsd generic linux macosx mingw posix solaris
+
+LUA_A= liblua.a
+CORE_O= lapi.o lcode.o lctype.o ldebug.o ldo.o ldump.o lfunc.o lgc.o llex.o \
+ lmem.o lobject.o lopcodes.o lparser.o lstate.o lstring.o ltable.o \
+ ltm.o lundump.o lvm.o lzio.o
+LIB_O= lauxlib.o lbaselib.o lbitlib.o lcorolib.o ldblib.o liolib.o \
+ lmathlib.o loslib.o lstrlib.o ltablib.o lutf8lib.o loadlib.o linit.o
+BASE_O= $(CORE_O) $(LIB_O) $(MYOBJS)
+
+LUA_T= lua
+LUA_O= lua.o
+
+LUAC_T= luac
+LUAC_O= luac.o
+
+ALL_O= $(BASE_O) $(LUA_O) $(LUAC_O)
+ALL_T= $(LUA_A) $(LUA_T) $(LUAC_T)
+ALL_A= $(LUA_A)
+
+# Targets start here.
+default: $(PLAT)
+
+all: $(ALL_T)
+
+o: $(ALL_O)
+
+a: $(ALL_A)
+
+$(LUA_A): $(BASE_O)
+ $(AR) $@ $(BASE_O)
+ $(RANLIB) $@
+
+$(LUA_T): $(LUA_O) $(LUA_A)
+ $(CC) -o $@ $(LDFLAGS) $(LUA_O) $(LUA_A) $(LIBS)
+
+$(LUAC_T): $(LUAC_O) $(LUA_A)
+ $(CC) -o $@ $(LDFLAGS) $(LUAC_O) $(LUA_A) $(LIBS)
+
+clean:
+ $(RM) $(ALL_T) $(ALL_O)
+
+depend:
+ @$(CC) $(CFLAGS) -MM l*.c
+
+echo:
+ @echo "PLAT= $(PLAT)"
+ @echo "CC= $(CC)"
+ @echo "CFLAGS= $(CFLAGS)"
+ @echo "LDFLAGS= $(SYSLDFLAGS)"
+ @echo "LIBS= $(LIBS)"
+ @echo "AR= $(AR)"
+ @echo "RANLIB= $(RANLIB)"
+ @echo "RM= $(RM)"
+
+# Convenience targets for popular platforms
+ALL= all
+
+none:
+ @echo "Please do 'make PLATFORM' where PLATFORM is one of these:"
+ @echo " $(PLATS)"
+
+aix:
+ $(MAKE) $(ALL) CC="xlc" CFLAGS="-O2 -DLUA_USE_POSIX -DLUA_USE_DLOPEN" SYSLIBS="-ldl" SYSLDFLAGS="-brtl -bexpall"
+
+bsd:
+ $(MAKE) $(ALL) SYSCFLAGS="-DLUA_USE_POSIX -DLUA_USE_DLOPEN" SYSLIBS="-Wl,-E"
+
+c89:
+ $(MAKE) $(ALL) SYSCFLAGS="-DLUA_USE_C89" CC="gcc -std=c89"
+ @echo ''
+ @echo '*** C89 does not guarantee 64-bit integers for Lua.'
+ @echo ''
+
+
+freebsd:
+ $(MAKE) $(ALL) SYSCFLAGS="-DLUA_USE_LINUX" SYSLIBS="-Wl,-E -lreadline"
+
+generic: $(ALL)
+
+linux:
+ $(MAKE) $(ALL) SYSCFLAGS="-DLUA_USE_LINUX" SYSLIBS="-Wl,-E -ldl -lreadline"
+
+macosx:
+ $(MAKE) $(ALL) SYSCFLAGS="-DLUA_USE_MACOSX" SYSLIBS="-lreadline" CC=cc
+
+mingw:
+ $(MAKE) "LUA_A=lua53.dll" "LUA_T=lua.exe" \
+ "AR=$(CC) -shared -o" "RANLIB=strip --strip-unneeded" \
+ "SYSCFLAGS=-DLUA_BUILD_AS_DLL" "SYSLIBS=" "SYSLDFLAGS=-s" lua.exe
+ $(MAKE) "LUAC_T=luac.exe" luac.exe
+
+posix:
+ $(MAKE) $(ALL) SYSCFLAGS="-DLUA_USE_POSIX"
+
+solaris:
+ $(MAKE) $(ALL) SYSCFLAGS="-DLUA_USE_POSIX -DLUA_USE_DLOPEN -D_REENTRANT" SYSLIBS="-ldl"
+
+# list targets that do not create files (but not all makes understand .PHONY)
+.PHONY: all $(PLATS) default o a clean depend echo none
+
+# DO NOT DELETE
+
+lapi.o: lapi.c lprefix.h lua.h luaconf.h lapi.h llimits.h lstate.h \
+ lobject.h ltm.h lzio.h lmem.h ldebug.h ldo.h lfunc.h lgc.h lstring.h \
+ ltable.h lundump.h lvm.h
+lauxlib.o: lauxlib.c lprefix.h lua.h luaconf.h lauxlib.h
+lbaselib.o: lbaselib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h
+lbitlib.o: lbitlib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h
+lcode.o: lcode.c lprefix.h lua.h luaconf.h lcode.h llex.h lobject.h \
+ llimits.h lzio.h lmem.h lopcodes.h lparser.h ldebug.h lstate.h ltm.h \
+ ldo.h lgc.h lstring.h ltable.h lvm.h
+lcorolib.o: lcorolib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h
+lctype.o: lctype.c lprefix.h lctype.h lua.h luaconf.h llimits.h
+ldblib.o: ldblib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h
+ldebug.o: ldebug.c lprefix.h lua.h luaconf.h lapi.h llimits.h lstate.h \
+ lobject.h ltm.h lzio.h lmem.h lcode.h llex.h lopcodes.h lparser.h \
+ ldebug.h ldo.h lfunc.h lstring.h lgc.h ltable.h lvm.h
+ldo.o: ldo.c lprefix.h lua.h luaconf.h lapi.h llimits.h lstate.h \
+ lobject.h ltm.h lzio.h lmem.h ldebug.h ldo.h lfunc.h lgc.h lopcodes.h \
+ lparser.h lstring.h ltable.h lundump.h lvm.h
+ldump.o: ldump.c lprefix.h lua.h luaconf.h lobject.h llimits.h lstate.h \
+ ltm.h lzio.h lmem.h lundump.h
+lfunc.o: lfunc.c lprefix.h lua.h luaconf.h lfunc.h lobject.h llimits.h \
+ lgc.h lstate.h ltm.h lzio.h lmem.h
+lgc.o: lgc.c lprefix.h lua.h luaconf.h ldebug.h lstate.h lobject.h \
+ llimits.h ltm.h lzio.h lmem.h ldo.h lfunc.h lgc.h lstring.h ltable.h
+linit.o: linit.c lprefix.h lua.h luaconf.h lualib.h lauxlib.h
+liolib.o: liolib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h
+llex.o: llex.c lprefix.h lua.h luaconf.h lctype.h llimits.h ldo.h \
+ lobject.h lstate.h ltm.h lzio.h lmem.h lgc.h llex.h lparser.h lstring.h \
+ ltable.h
+lmathlib.o: lmathlib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h
+lmem.o: lmem.c lprefix.h lua.h luaconf.h ldebug.h lstate.h lobject.h \
+ llimits.h ltm.h lzio.h lmem.h ldo.h lgc.h
+loadlib.o: loadlib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h
+lobject.o: lobject.c lprefix.h lua.h luaconf.h lctype.h llimits.h \
+ ldebug.h lstate.h lobject.h ltm.h lzio.h lmem.h ldo.h lstring.h lgc.h \
+ lvm.h
+lopcodes.o: lopcodes.c lprefix.h lopcodes.h llimits.h lua.h luaconf.h
+loslib.o: loslib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h
+lparser.o: lparser.c lprefix.h lua.h luaconf.h lcode.h llex.h lobject.h \
+ llimits.h lzio.h lmem.h lopcodes.h lparser.h ldebug.h lstate.h ltm.h \
+ ldo.h lfunc.h lstring.h lgc.h ltable.h
+lstate.o: lstate.c lprefix.h lua.h luaconf.h lapi.h llimits.h lstate.h \
+ lobject.h ltm.h lzio.h lmem.h ldebug.h ldo.h lfunc.h lgc.h llex.h \
+ lstring.h ltable.h
+lstring.o: lstring.c lprefix.h lua.h luaconf.h ldebug.h lstate.h \
+ lobject.h llimits.h ltm.h lzio.h lmem.h ldo.h lstring.h lgc.h
+lstrlib.o: lstrlib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h
+ltable.o: ltable.c lprefix.h lua.h luaconf.h ldebug.h lstate.h lobject.h \
+ llimits.h ltm.h lzio.h lmem.h ldo.h lgc.h lstring.h ltable.h lvm.h
+ltablib.o: ltablib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h
+ltm.o: ltm.c lprefix.h lua.h luaconf.h ldebug.h lstate.h lobject.h \
+ llimits.h ltm.h lzio.h lmem.h ldo.h lstring.h lgc.h ltable.h lvm.h
+lua.o: lua.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h
+luac.o: luac.c lprefix.h lua.h luaconf.h lauxlib.h lobject.h llimits.h \
+ lstate.h ltm.h lzio.h lmem.h lundump.h ldebug.h lopcodes.h
+lundump.o: lundump.c lprefix.h lua.h luaconf.h ldebug.h lstate.h \
+ lobject.h llimits.h ltm.h lzio.h lmem.h ldo.h lfunc.h lstring.h lgc.h \
+ lundump.h
+lutf8lib.o: lutf8lib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h
+lvm.o: lvm.c lprefix.h lua.h luaconf.h ldebug.h lstate.h lobject.h \
+ llimits.h ltm.h lzio.h lmem.h ldo.h lfunc.h lgc.h lopcodes.h lstring.h \
+ ltable.h lvm.h
+lzio.o: lzio.c lprefix.h lua.h luaconf.h llimits.h lmem.h lstate.h \
+ lobject.h ltm.h lzio.h
+
+# (end of Makefile)
diff --git a/src/lapi.c b/src/lapi.c
new file mode 100644
index 0000000000..fbfafa304f
--- /dev/null
+++ b/src/lapi.c
@@ -0,0 +1,1270 @@
+/*
+** $Id: lapi.c,v 2.244 2014/12/26 14:43:45 roberto Exp $
+** Lua API
+** See Copyright Notice in lua.h
+*/
+
+#define lapi_c
+#define LUA_CORE
+
+#include "lprefix.h"
+
+
+#include
+#include
+
+#include "lua.h"
+
+#include "lapi.h"
+#include "ldebug.h"
+#include "ldo.h"
+#include "lfunc.h"
+#include "lgc.h"
+#include "lmem.h"
+#include "lobject.h"
+#include "lstate.h"
+#include "lstring.h"
+#include "ltable.h"
+#include "ltm.h"
+#include "lundump.h"
+#include "lvm.h"
+
+
+
+const char lua_ident[] =
+ "$LuaVersion: " LUA_COPYRIGHT " $"
+ "$LuaAuthors: " LUA_AUTHORS " $";
+
+
+/* value at a non-valid index */
+#define NONVALIDVALUE cast(TValue *, luaO_nilobject)
+
+/* corresponding test */
+#define isvalid(o) ((o) != luaO_nilobject)
+
+/* test for pseudo index */
+#define ispseudo(i) ((i) <= LUA_REGISTRYINDEX)
+
+/* test for upvalue */
+#define isupvalue(i) ((i) < LUA_REGISTRYINDEX)
+
+/* test for valid but not pseudo index */
+#define isstackindex(i, o) (isvalid(o) && !ispseudo(i))
+
+#define api_checkvalidindex(o) api_check(isvalid(o), "invalid index")
+
+#define api_checkstackindex(i, o) \
+ api_check(isstackindex(i, o), "index not in the stack")
+
+
+static TValue *index2addr (lua_State *L, int idx) {
+ CallInfo *ci = L->ci;
+ if (idx > 0) {
+ TValue *o = ci->func + idx;
+ api_check(idx <= ci->top - (ci->func + 1), "unacceptable index");
+ if (o >= L->top) return NONVALIDVALUE;
+ else return o;
+ }
+ else if (!ispseudo(idx)) { /* negative index */
+ api_check(idx != 0 && -idx <= L->top - (ci->func + 1), "invalid index");
+ return L->top + idx;
+ }
+ else if (idx == LUA_REGISTRYINDEX)
+ return &G(L)->l_registry;
+ else { /* upvalues */
+ idx = LUA_REGISTRYINDEX - idx;
+ api_check(idx <= MAXUPVAL + 1, "upvalue index too large");
+ if (ttislcf(ci->func)) /* light C function? */
+ return NONVALIDVALUE; /* it has no upvalues */
+ else {
+ CClosure *func = clCvalue(ci->func);
+ return (idx <= func->nupvalues) ? &func->upvalue[idx-1] : NONVALIDVALUE;
+ }
+ }
+}
+
+
+/*
+** to be called by 'lua_checkstack' in protected mode, to grow stack
+** capturing memory errors
+*/
+static void growstack (lua_State *L, void *ud) {
+ int size = *(int *)ud;
+ luaD_growstack(L, size);
+}
+
+
+LUA_API int lua_checkstack (lua_State *L, int n) {
+ int res;
+ CallInfo *ci = L->ci;
+ lua_lock(L);
+ api_check(n >= 0, "negative 'n'");
+ if (L->stack_last - L->top > n) /* stack large enough? */
+ res = 1; /* yes; check is OK */
+ else { /* no; need to grow stack */
+ int inuse = cast_int(L->top - L->stack) + EXTRA_STACK;
+ if (inuse > LUAI_MAXSTACK - n) /* can grow without overflow? */
+ res = 0; /* no */
+ else /* try to grow stack */
+ res = (luaD_rawrunprotected(L, &growstack, &n) == LUA_OK);
+ }
+ if (res && ci->top < L->top + n)
+ ci->top = L->top + n; /* adjust frame top */
+ lua_unlock(L);
+ return res;
+}
+
+
+LUA_API void lua_xmove (lua_State *from, lua_State *to, int n) {
+ int i;
+ if (from == to) return;
+ lua_lock(to);
+ api_checknelems(from, n);
+ api_check(G(from) == G(to), "moving among independent states");
+ api_check(to->ci->top - to->top >= n, "not enough elements to move");
+ from->top -= n;
+ for (i = 0; i < n; i++) {
+ setobj2s(to, to->top++, from->top + i);
+ }
+ lua_unlock(to);
+}
+
+
+LUA_API lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf) {
+ lua_CFunction old;
+ lua_lock(L);
+ old = G(L)->panic;
+ G(L)->panic = panicf;
+ lua_unlock(L);
+ return old;
+}
+
+
+LUA_API const lua_Number *lua_version (lua_State *L) {
+ static const lua_Number version = LUA_VERSION_NUM;
+ if (L == NULL) return &version;
+ else return G(L)->version;
+}
+
+
+
+/*
+** basic stack manipulation
+*/
+
+
+/*
+** convert an acceptable stack index into an absolute index
+*/
+LUA_API int lua_absindex (lua_State *L, int idx) {
+ return (idx > 0 || ispseudo(idx))
+ ? idx
+ : cast_int(L->top - L->ci->func + idx);
+}
+
+
+LUA_API int lua_gettop (lua_State *L) {
+ return cast_int(L->top - (L->ci->func + 1));
+}
+
+
+LUA_API void lua_settop (lua_State *L, int idx) {
+ StkId func = L->ci->func;
+ lua_lock(L);
+ if (idx >= 0) {
+ api_check(idx <= L->stack_last - (func + 1), "new top too large");
+ while (L->top < (func + 1) + idx)
+ setnilvalue(L->top++);
+ L->top = (func + 1) + idx;
+ }
+ else {
+ api_check(-(idx+1) <= (L->top - (func + 1)), "invalid new top");
+ L->top += idx+1; /* 'subtract' index (index is negative) */
+ }
+ lua_unlock(L);
+}
+
+
+/*
+** Reverse the stack segment from 'from' to 'to'
+** (auxiliary to 'lua_rotate')
+*/
+static void reverse (lua_State *L, StkId from, StkId to) {
+ for (; from < to; from++, to--) {
+ TValue temp;
+ setobj(L, &temp, from);
+ setobjs2s(L, from, to);
+ setobj2s(L, to, &temp);
+ }
+}
+
+
+/*
+** Let x = AB, where A is a prefix of length 'n'. Then,
+** rotate x n == BA. But BA == (A^r . B^r)^r.
+*/
+LUA_API void lua_rotate (lua_State *L, int idx, int n) {
+ StkId p, t, m;
+ lua_lock(L);
+ t = L->top - 1; /* end of stack segment being rotated */
+ p = index2addr(L, idx); /* start of segment */
+ api_checkstackindex(idx, p);
+ api_check((n >= 0 ? n : -n) <= (t - p + 1), "invalid 'n'");
+ m = (n >= 0 ? t - n : p - n - 1); /* end of prefix */
+ reverse(L, p, m); /* reverse the prefix with length 'n' */
+ reverse(L, m + 1, t); /* reverse the suffix */
+ reverse(L, p, t); /* reverse the entire segment */
+ lua_unlock(L);
+}
+
+
+LUA_API void lua_copy (lua_State *L, int fromidx, int toidx) {
+ TValue *fr, *to;
+ lua_lock(L);
+ fr = index2addr(L, fromidx);
+ to = index2addr(L, toidx);
+ api_checkvalidindex(to);
+ setobj(L, to, fr);
+ if (isupvalue(toidx)) /* function upvalue? */
+ luaC_barrier(L, clCvalue(L->ci->func), fr);
+ /* LUA_REGISTRYINDEX does not need gc barrier
+ (collector revisits it before finishing collection) */
+ lua_unlock(L);
+}
+
+
+LUA_API void lua_pushvalue (lua_State *L, int idx) {
+ lua_lock(L);
+ setobj2s(L, L->top, index2addr(L, idx));
+ api_incr_top(L);
+ lua_unlock(L);
+}
+
+
+
+/*
+** access functions (stack -> C)
+*/
+
+
+LUA_API int lua_type (lua_State *L, int idx) {
+ StkId o = index2addr(L, idx);
+ return (isvalid(o) ? ttnov(o) : LUA_TNONE);
+}
+
+
+LUA_API const char *lua_typename (lua_State *L, int t) {
+ UNUSED(L);
+ api_check(LUA_TNONE <= t && t < LUA_NUMTAGS, "invalid tag");
+ return ttypename(t);
+}
+
+
+LUA_API int lua_iscfunction (lua_State *L, int idx) {
+ StkId o = index2addr(L, idx);
+ return (ttislcf(o) || (ttisCclosure(o)));
+}
+
+
+LUA_API int lua_isinteger (lua_State *L, int idx) {
+ StkId o = index2addr(L, idx);
+ return ttisinteger(o);
+}
+
+
+LUA_API int lua_isnumber (lua_State *L, int idx) {
+ lua_Number n;
+ const TValue *o = index2addr(L, idx);
+ return tonumber(o, &n);
+}
+
+
+LUA_API int lua_isstring (lua_State *L, int idx) {
+ const TValue *o = index2addr(L, idx);
+ return (ttisstring(o) || cvt2str(o));
+}
+
+
+LUA_API int lua_isuserdata (lua_State *L, int idx) {
+ const TValue *o = index2addr(L, idx);
+ return (ttisfulluserdata(o) || ttislightuserdata(o));
+}
+
+
+LUA_API int lua_rawequal (lua_State *L, int index1, int index2) {
+ StkId o1 = index2addr(L, index1);
+ StkId o2 = index2addr(L, index2);
+ return (isvalid(o1) && isvalid(o2)) ? luaV_rawequalobj(o1, o2) : 0;
+}
+
+
+LUA_API void lua_arith (lua_State *L, int op) {
+ lua_lock(L);
+ if (op != LUA_OPUNM && op != LUA_OPBNOT)
+ api_checknelems(L, 2); /* all other operations expect two operands */
+ else { /* for unary operations, add fake 2nd operand */
+ api_checknelems(L, 1);
+ setobjs2s(L, L->top, L->top - 1);
+ L->top++;
+ }
+ /* first operand at top - 2, second at top - 1; result go to top - 2 */
+ luaO_arith(L, op, L->top - 2, L->top - 1, L->top - 2);
+ L->top--; /* remove second operand */
+ lua_unlock(L);
+}
+
+
+LUA_API int lua_compare (lua_State *L, int index1, int index2, int op) {
+ StkId o1, o2;
+ int i = 0;
+ lua_lock(L); /* may call tag method */
+ o1 = index2addr(L, index1);
+ o2 = index2addr(L, index2);
+ if (isvalid(o1) && isvalid(o2)) {
+ switch (op) {
+ case LUA_OPEQ: i = luaV_equalobj(L, o1, o2); break;
+ case LUA_OPLT: i = luaV_lessthan(L, o1, o2); break;
+ case LUA_OPLE: i = luaV_lessequal(L, o1, o2); break;
+ default: api_check(0, "invalid option");
+ }
+ }
+ lua_unlock(L);
+ return i;
+}
+
+
+LUA_API size_t lua_stringtonumber (lua_State *L, const char *s) {
+ size_t sz = luaO_str2num(s, L->top);
+ if (sz != 0)
+ api_incr_top(L);
+ return sz;
+}
+
+
+LUA_API lua_Number lua_tonumberx (lua_State *L, int idx, int *pisnum) {
+ lua_Number n;
+ const TValue *o = index2addr(L, idx);
+ int isnum = tonumber(o, &n);
+ if (!isnum)
+ n = 0; /* call to 'tonumber' may change 'n' even if it fails */
+ if (pisnum) *pisnum = isnum;
+ return n;
+}
+
+
+LUA_API lua_Integer lua_tointegerx (lua_State *L, int idx, int *pisnum) {
+ lua_Integer res;
+ const TValue *o = index2addr(L, idx);
+ int isnum = tointeger(o, &res);
+ if (!isnum)
+ res = 0; /* call to 'tointeger' may change 'n' even if it fails */
+ if (pisnum) *pisnum = isnum;
+ return res;
+}
+
+
+LUA_API int lua_toboolean (lua_State *L, int idx) {
+ const TValue *o = index2addr(L, idx);
+ return !l_isfalse(o);
+}
+
+
+LUA_API const char *lua_tolstring (lua_State *L, int idx, size_t *len) {
+ StkId o = index2addr(L, idx);
+ if (!ttisstring(o)) {
+ if (!cvt2str(o)) { /* not convertible? */
+ if (len != NULL) *len = 0;
+ return NULL;
+ }
+ lua_lock(L); /* 'luaO_tostring' may create a new string */
+ luaC_checkGC(L);
+ o = index2addr(L, idx); /* previous call may reallocate the stack */
+ luaO_tostring(L, o);
+ lua_unlock(L);
+ }
+ if (len != NULL) *len = tsvalue(o)->len;
+ return svalue(o);
+}
+
+
+LUA_API size_t lua_rawlen (lua_State *L, int idx) {
+ StkId o = index2addr(L, idx);
+ switch (ttnov(o)) {
+ case LUA_TSTRING: return tsvalue(o)->len;
+ case LUA_TUSERDATA: return uvalue(o)->len;
+ case LUA_TTABLE: return luaH_getn(hvalue(o));
+ default: return 0;
+ }
+}
+
+
+LUA_API lua_CFunction lua_tocfunction (lua_State *L, int idx) {
+ StkId o = index2addr(L, idx);
+ if (ttislcf(o)) return fvalue(o);
+ else if (ttisCclosure(o))
+ return clCvalue(o)->f;
+ else return NULL; /* not a C function */
+}
+
+
+LUA_API void *lua_touserdata (lua_State *L, int idx) {
+ StkId o = index2addr(L, idx);
+ switch (ttnov(o)) {
+ case LUA_TUSERDATA: return getudatamem(uvalue(o));
+ case LUA_TLIGHTUSERDATA: return pvalue(o);
+ default: return NULL;
+ }
+}
+
+
+LUA_API lua_State *lua_tothread (lua_State *L, int idx) {
+ StkId o = index2addr(L, idx);
+ return (!ttisthread(o)) ? NULL : thvalue(o);
+}
+
+
+LUA_API const void *lua_topointer (lua_State *L, int idx) {
+ StkId o = index2addr(L, idx);
+ switch (ttype(o)) {
+ case LUA_TTABLE: return hvalue(o);
+ case LUA_TLCL: return clLvalue(o);
+ case LUA_TCCL: return clCvalue(o);
+ case LUA_TLCF: return cast(void *, cast(size_t, fvalue(o)));
+ case LUA_TTHREAD: return thvalue(o);
+ case LUA_TUSERDATA:
+ case LUA_TLIGHTUSERDATA:
+ return lua_touserdata(L, idx);
+ default: return NULL;
+ }
+}
+
+
+
+/*
+** push functions (C -> stack)
+*/
+
+
+LUA_API void lua_pushnil (lua_State *L) {
+ lua_lock(L);
+ setnilvalue(L->top);
+ api_incr_top(L);
+ lua_unlock(L);
+}
+
+
+LUA_API void lua_pushnumber (lua_State *L, lua_Number n) {
+ lua_lock(L);
+ setfltvalue(L->top, n);
+ api_incr_top(L);
+ lua_unlock(L);
+}
+
+
+LUA_API void lua_pushinteger (lua_State *L, lua_Integer n) {
+ lua_lock(L);
+ setivalue(L->top, n);
+ api_incr_top(L);
+ lua_unlock(L);
+}
+
+
+LUA_API const char *lua_pushlstring (lua_State *L, const char *s, size_t len) {
+ TString *ts;
+ lua_lock(L);
+ luaC_checkGC(L);
+ ts = luaS_newlstr(L, s, len);
+ setsvalue2s(L, L->top, ts);
+ api_incr_top(L);
+ lua_unlock(L);
+ return getstr(ts);
+}
+
+
+LUA_API const char *lua_pushstring (lua_State *L, const char *s) {
+ if (s == NULL) {
+ lua_pushnil(L);
+ return NULL;
+ }
+ else {
+ TString *ts;
+ lua_lock(L);
+ luaC_checkGC(L);
+ ts = luaS_new(L, s);
+ setsvalue2s(L, L->top, ts);
+ api_incr_top(L);
+ lua_unlock(L);
+ return getstr(ts);
+ }
+}
+
+
+LUA_API const char *lua_pushvfstring (lua_State *L, const char *fmt,
+ va_list argp) {
+ const char *ret;
+ lua_lock(L);
+ luaC_checkGC(L);
+ ret = luaO_pushvfstring(L, fmt, argp);
+ lua_unlock(L);
+ return ret;
+}
+
+
+LUA_API const char *lua_pushfstring (lua_State *L, const char *fmt, ...) {
+ const char *ret;
+ va_list argp;
+ lua_lock(L);
+ luaC_checkGC(L);
+ va_start(argp, fmt);
+ ret = luaO_pushvfstring(L, fmt, argp);
+ va_end(argp);
+ lua_unlock(L);
+ return ret;
+}
+
+
+LUA_API void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n) {
+ lua_lock(L);
+ if (n == 0) {
+ setfvalue(L->top, fn);
+ }
+ else {
+ CClosure *cl;
+ api_checknelems(L, n);
+ api_check(n <= MAXUPVAL, "upvalue index too large");
+ luaC_checkGC(L);
+ cl = luaF_newCclosure(L, n);
+ cl->f = fn;
+ L->top -= n;
+ while (n--) {
+ setobj2n(L, &cl->upvalue[n], L->top + n);
+ /* does not need barrier because closure is white */
+ }
+ setclCvalue(L, L->top, cl);
+ }
+ api_incr_top(L);
+ lua_unlock(L);
+}
+
+
+LUA_API void lua_pushboolean (lua_State *L, int b) {
+ lua_lock(L);
+ setbvalue(L->top, (b != 0)); /* ensure that true is 1 */
+ api_incr_top(L);
+ lua_unlock(L);
+}
+
+
+LUA_API void lua_pushlightuserdata (lua_State *L, void *p) {
+ lua_lock(L);
+ setpvalue(L->top, p);
+ api_incr_top(L);
+ lua_unlock(L);
+}
+
+
+LUA_API int lua_pushthread (lua_State *L) {
+ lua_lock(L);
+ setthvalue(L, L->top, L);
+ api_incr_top(L);
+ lua_unlock(L);
+ return (G(L)->mainthread == L);
+}
+
+
+
+/*
+** get functions (Lua -> stack)
+*/
+
+
+LUA_API int lua_getglobal (lua_State *L, const char *name) {
+ Table *reg = hvalue(&G(L)->l_registry);
+ const TValue *gt; /* global table */
+ lua_lock(L);
+ gt = luaH_getint(reg, LUA_RIDX_GLOBALS);
+ setsvalue2s(L, L->top++, luaS_new(L, name));
+ luaV_gettable(L, gt, L->top - 1, L->top - 1);
+ lua_unlock(L);
+ return ttnov(L->top - 1);
+}
+
+
+LUA_API int lua_gettable (lua_State *L, int idx) {
+ StkId t;
+ lua_lock(L);
+ t = index2addr(L, idx);
+ luaV_gettable(L, t, L->top - 1, L->top - 1);
+ lua_unlock(L);
+ return ttnov(L->top - 1);
+}
+
+
+LUA_API int lua_getfield (lua_State *L, int idx, const char *k) {
+ StkId t;
+ lua_lock(L);
+ t = index2addr(L, idx);
+ setsvalue2s(L, L->top, luaS_new(L, k));
+ api_incr_top(L);
+ luaV_gettable(L, t, L->top - 1, L->top - 1);
+ lua_unlock(L);
+ return ttnov(L->top - 1);
+}
+
+
+LUA_API int lua_geti (lua_State *L, int idx, lua_Integer n) {
+ StkId t;
+ lua_lock(L);
+ t = index2addr(L, idx);
+ setivalue(L->top, n);
+ api_incr_top(L);
+ luaV_gettable(L, t, L->top - 1, L->top - 1);
+ lua_unlock(L);
+ return ttnov(L->top - 1);
+}
+
+
+LUA_API int lua_rawget (lua_State *L, int idx) {
+ StkId t;
+ lua_lock(L);
+ t = index2addr(L, idx);
+ api_check(ttistable(t), "table expected");
+ setobj2s(L, L->top - 1, luaH_get(hvalue(t), L->top - 1));
+ lua_unlock(L);
+ return ttnov(L->top - 1);
+}
+
+
+LUA_API int lua_rawgeti (lua_State *L, int idx, lua_Integer n) {
+ StkId t;
+ lua_lock(L);
+ t = index2addr(L, idx);
+ api_check(ttistable(t), "table expected");
+ setobj2s(L, L->top, luaH_getint(hvalue(t), n));
+ api_incr_top(L);
+ lua_unlock(L);
+ return ttnov(L->top - 1);
+}
+
+
+LUA_API int lua_rawgetp (lua_State *L, int idx, const void *p) {
+ StkId t;
+ TValue k;
+ lua_lock(L);
+ t = index2addr(L, idx);
+ api_check(ttistable(t), "table expected");
+ setpvalue(&k, cast(void *, p));
+ setobj2s(L, L->top, luaH_get(hvalue(t), &k));
+ api_incr_top(L);
+ lua_unlock(L);
+ return ttnov(L->top - 1);
+}
+
+
+LUA_API void lua_createtable (lua_State *L, int narray, int nrec) {
+ Table *t;
+ lua_lock(L);
+ luaC_checkGC(L);
+ t = luaH_new(L);
+ sethvalue(L, L->top, t);
+ api_incr_top(L);
+ if (narray > 0 || nrec > 0)
+ luaH_resize(L, t, narray, nrec);
+ lua_unlock(L);
+}
+
+
+LUA_API int lua_getmetatable (lua_State *L, int objindex) {
+ const TValue *obj;
+ Table *mt;
+ int res = 0;
+ lua_lock(L);
+ obj = index2addr(L, objindex);
+ switch (ttnov(obj)) {
+ case LUA_TTABLE:
+ mt = hvalue(obj)->metatable;
+ break;
+ case LUA_TUSERDATA:
+ mt = uvalue(obj)->metatable;
+ break;
+ default:
+ mt = G(L)->mt[ttnov(obj)];
+ break;
+ }
+ if (mt != NULL) {
+ sethvalue(L, L->top, mt);
+ api_incr_top(L);
+ res = 1;
+ }
+ lua_unlock(L);
+ return res;
+}
+
+
+LUA_API int lua_getuservalue (lua_State *L, int idx) {
+ StkId o;
+ lua_lock(L);
+ o = index2addr(L, idx);
+ api_check(ttisfulluserdata(o), "full userdata expected");
+ getuservalue(L, uvalue(o), L->top);
+ api_incr_top(L);
+ lua_unlock(L);
+ return ttnov(L->top - 1);
+}
+
+
+/*
+** set functions (stack -> Lua)
+*/
+
+
+LUA_API void lua_setglobal (lua_State *L, const char *name) {
+ Table *reg = hvalue(&G(L)->l_registry);
+ const TValue *gt; /* global table */
+ lua_lock(L);
+ api_checknelems(L, 1);
+ gt = luaH_getint(reg, LUA_RIDX_GLOBALS);
+ setsvalue2s(L, L->top++, luaS_new(L, name));
+ luaV_settable(L, gt, L->top - 1, L->top - 2);
+ L->top -= 2; /* pop value and key */
+ lua_unlock(L);
+}
+
+
+LUA_API void lua_settable (lua_State *L, int idx) {
+ StkId t;
+ lua_lock(L);
+ api_checknelems(L, 2);
+ t = index2addr(L, idx);
+ luaV_settable(L, t, L->top - 2, L->top - 1);
+ L->top -= 2; /* pop index and value */
+ lua_unlock(L);
+}
+
+
+LUA_API void lua_setfield (lua_State *L, int idx, const char *k) {
+ StkId t;
+ lua_lock(L);
+ api_checknelems(L, 1);
+ t = index2addr(L, idx);
+ setsvalue2s(L, L->top++, luaS_new(L, k));
+ luaV_settable(L, t, L->top - 1, L->top - 2);
+ L->top -= 2; /* pop value and key */
+ lua_unlock(L);
+}
+
+
+LUA_API void lua_seti (lua_State *L, int idx, lua_Integer n) {
+ StkId t;
+ lua_lock(L);
+ api_checknelems(L, 1);
+ t = index2addr(L, idx);
+ setivalue(L->top++, n);
+ luaV_settable(L, t, L->top - 1, L->top - 2);
+ L->top -= 2; /* pop value and key */
+ lua_unlock(L);
+}
+
+
+LUA_API void lua_rawset (lua_State *L, int idx) {
+ StkId o;
+ Table *t;
+ lua_lock(L);
+ api_checknelems(L, 2);
+ o = index2addr(L, idx);
+ api_check(ttistable(o), "table expected");
+ t = hvalue(o);
+ setobj2t(L, luaH_set(L, t, L->top-2), L->top-1);
+ invalidateTMcache(t);
+ luaC_barrierback(L, t, L->top-1);
+ L->top -= 2;
+ lua_unlock(L);
+}
+
+
+LUA_API void lua_rawseti (lua_State *L, int idx, lua_Integer n) {
+ StkId o;
+ Table *t;
+ lua_lock(L);
+ api_checknelems(L, 1);
+ o = index2addr(L, idx);
+ api_check(ttistable(o), "table expected");
+ t = hvalue(o);
+ luaH_setint(L, t, n, L->top - 1);
+ luaC_barrierback(L, t, L->top-1);
+ L->top--;
+ lua_unlock(L);
+}
+
+
+LUA_API void lua_rawsetp (lua_State *L, int idx, const void *p) {
+ StkId o;
+ Table *t;
+ TValue k;
+ lua_lock(L);
+ api_checknelems(L, 1);
+ o = index2addr(L, idx);
+ api_check(ttistable(o), "table expected");
+ t = hvalue(o);
+ setpvalue(&k, cast(void *, p));
+ setobj2t(L, luaH_set(L, t, &k), L->top - 1);
+ luaC_barrierback(L, t, L->top - 1);
+ L->top--;
+ lua_unlock(L);
+}
+
+
+LUA_API int lua_setmetatable (lua_State *L, int objindex) {
+ TValue *obj;
+ Table *mt;
+ lua_lock(L);
+ api_checknelems(L, 1);
+ obj = index2addr(L, objindex);
+ if (ttisnil(L->top - 1))
+ mt = NULL;
+ else {
+ api_check(ttistable(L->top - 1), "table expected");
+ mt = hvalue(L->top - 1);
+ }
+ switch (ttnov(obj)) {
+ case LUA_TTABLE: {
+ hvalue(obj)->metatable = mt;
+ if (mt) {
+ luaC_objbarrier(L, gcvalue(obj), mt);
+ luaC_checkfinalizer(L, gcvalue(obj), mt);
+ }
+ break;
+ }
+ case LUA_TUSERDATA: {
+ uvalue(obj)->metatable = mt;
+ if (mt) {
+ luaC_objbarrier(L, uvalue(obj), mt);
+ luaC_checkfinalizer(L, gcvalue(obj), mt);
+ }
+ break;
+ }
+ default: {
+ G(L)->mt[ttnov(obj)] = mt;
+ break;
+ }
+ }
+ L->top--;
+ lua_unlock(L);
+ return 1;
+}
+
+
+LUA_API void lua_setuservalue (lua_State *L, int idx) {
+ StkId o;
+ lua_lock(L);
+ api_checknelems(L, 1);
+ o = index2addr(L, idx);
+ api_check(ttisfulluserdata(o), "full userdata expected");
+ setuservalue(L, uvalue(o), L->top - 1);
+ luaC_barrier(L, gcvalue(o), L->top - 1);
+ L->top--;
+ lua_unlock(L);
+}
+
+
+/*
+** 'load' and 'call' functions (run Lua code)
+*/
+
+
+#define checkresults(L,na,nr) \
+ api_check((nr) == LUA_MULTRET || (L->ci->top - L->top >= (nr) - (na)), \
+ "results from function overflow current stack size")
+
+
+LUA_API void lua_callk (lua_State *L, int nargs, int nresults,
+ lua_KContext ctx, lua_KFunction k) {
+ StkId func;
+ lua_lock(L);
+ api_check(k == NULL || !isLua(L->ci),
+ "cannot use continuations inside hooks");
+ api_checknelems(L, nargs+1);
+ api_check(L->status == LUA_OK, "cannot do calls on non-normal thread");
+ checkresults(L, nargs, nresults);
+ func = L->top - (nargs+1);
+ if (k != NULL && L->nny == 0) { /* need to prepare continuation? */
+ L->ci->u.c.k = k; /* save continuation */
+ L->ci->u.c.ctx = ctx; /* save context */
+ luaD_call(L, func, nresults, 1); /* do the call */
+ }
+ else /* no continuation or no yieldable */
+ luaD_call(L, func, nresults, 0); /* just do the call */
+ adjustresults(L, nresults);
+ lua_unlock(L);
+}
+
+
+
+/*
+** Execute a protected call.
+*/
+struct CallS { /* data to 'f_call' */
+ StkId func;
+ int nresults;
+};
+
+
+static void f_call (lua_State *L, void *ud) {
+ struct CallS *c = cast(struct CallS *, ud);
+ luaD_call(L, c->func, c->nresults, 0);
+}
+
+
+
+LUA_API int lua_pcallk (lua_State *L, int nargs, int nresults, int errfunc,
+ lua_KContext ctx, lua_KFunction k) {
+ struct CallS c;
+ int status;
+ ptrdiff_t func;
+ lua_lock(L);
+ api_check(k == NULL || !isLua(L->ci),
+ "cannot use continuations inside hooks");
+ api_checknelems(L, nargs+1);
+ api_check(L->status == LUA_OK, "cannot do calls on non-normal thread");
+ checkresults(L, nargs, nresults);
+ if (errfunc == 0)
+ func = 0;
+ else {
+ StkId o = index2addr(L, errfunc);
+ api_checkstackindex(errfunc, o);
+ func = savestack(L, o);
+ }
+ c.func = L->top - (nargs+1); /* function to be called */
+ if (k == NULL || L->nny > 0) { /* no continuation or no yieldable? */
+ c.nresults = nresults; /* do a 'conventional' protected call */
+ status = luaD_pcall(L, f_call, &c, savestack(L, c.func), func);
+ }
+ else { /* prepare continuation (call is already protected by 'resume') */
+ CallInfo *ci = L->ci;
+ ci->u.c.k = k; /* save continuation */
+ ci->u.c.ctx = ctx; /* save context */
+ /* save information for error recovery */
+ ci->extra = savestack(L, c.func);
+ ci->u.c.old_errfunc = L->errfunc;
+ L->errfunc = func;
+ setoah(ci->callstatus, L->allowhook); /* save value of 'allowhook' */
+ ci->callstatus |= CIST_YPCALL; /* function can do error recovery */
+ luaD_call(L, c.func, nresults, 1); /* do the call */
+ ci->callstatus &= ~CIST_YPCALL;
+ L->errfunc = ci->u.c.old_errfunc;
+ status = LUA_OK; /* if it is here, there were no errors */
+ }
+ adjustresults(L, nresults);
+ lua_unlock(L);
+ return status;
+}
+
+
+LUA_API int lua_load (lua_State *L, lua_Reader reader, void *data,
+ const char *chunkname, const char *mode) {
+ ZIO z;
+ int status;
+ lua_lock(L);
+ if (!chunkname) chunkname = "?";
+ luaZ_init(L, &z, reader, data);
+ status = luaD_protectedparser(L, &z, chunkname, mode);
+ if (status == LUA_OK) { /* no errors? */
+ LClosure *f = clLvalue(L->top - 1); /* get newly created function */
+ if (f->nupvalues >= 1) { /* does it have an upvalue? */
+ /* get global table from registry */
+ Table *reg = hvalue(&G(L)->l_registry);
+ const TValue *gt = luaH_getint(reg, LUA_RIDX_GLOBALS);
+ /* set global table as 1st upvalue of 'f' (may be LUA_ENV) */
+ setobj(L, f->upvals[0]->v, gt);
+ luaC_upvalbarrier(L, f->upvals[0]);
+ }
+ }
+ lua_unlock(L);
+ return status;
+}
+
+
+LUA_API int lua_dump (lua_State *L, lua_Writer writer, void *data, int strip) {
+ int status;
+ TValue *o;
+ lua_lock(L);
+ api_checknelems(L, 1);
+ o = L->top - 1;
+ if (isLfunction(o))
+ status = luaU_dump(L, getproto(o), writer, data, strip);
+ else
+ status = 1;
+ lua_unlock(L);
+ return status;
+}
+
+
+LUA_API int lua_status (lua_State *L) {
+ return L->status;
+}
+
+
+/*
+** Garbage-collection function
+*/
+
+LUA_API int lua_gc (lua_State *L, int what, int data) {
+ int res = 0;
+ global_State *g;
+ lua_lock(L);
+ g = G(L);
+ switch (what) {
+ case LUA_GCSTOP: {
+ g->gcrunning = 0;
+ break;
+ }
+ case LUA_GCRESTART: {
+ luaE_setdebt(g, 0);
+ g->gcrunning = 1;
+ break;
+ }
+ case LUA_GCCOLLECT: {
+ luaC_fullgc(L, 0);
+ break;
+ }
+ case LUA_GCCOUNT: {
+ /* GC values are expressed in Kbytes: #bytes/2^10 */
+ res = cast_int(gettotalbytes(g) >> 10);
+ break;
+ }
+ case LUA_GCCOUNTB: {
+ res = cast_int(gettotalbytes(g) & 0x3ff);
+ break;
+ }
+ case LUA_GCSTEP: {
+ l_mem debt = 1; /* =1 to signal that it did an actual step */
+ int oldrunning = g->gcrunning;
+ g->gcrunning = 1; /* allow GC to run */
+ if (data == 0) {
+ luaE_setdebt(g, -GCSTEPSIZE); /* to do a "small" step */
+ luaC_step(L);
+ }
+ else { /* add 'data' to total debt */
+ debt = cast(l_mem, data) * 1024 + g->GCdebt;
+ luaE_setdebt(g, debt);
+ luaC_checkGC(L);
+ }
+ g->gcrunning = oldrunning; /* restore previous state */
+ if (debt > 0 && g->gcstate == GCSpause) /* end of cycle? */
+ res = 1; /* signal it */
+ break;
+ }
+ case LUA_GCSETPAUSE: {
+ res = g->gcpause;
+ g->gcpause = data;
+ break;
+ }
+ case LUA_GCSETSTEPMUL: {
+ res = g->gcstepmul;
+ if (data < 40) data = 40; /* avoid ridiculous low values (and 0) */
+ g->gcstepmul = data;
+ break;
+ }
+ case LUA_GCISRUNNING: {
+ res = g->gcrunning;
+ break;
+ }
+ default: res = -1; /* invalid option */
+ }
+ lua_unlock(L);
+ return res;
+}
+
+
+
+/*
+** miscellaneous functions
+*/
+
+
+LUA_API int lua_error (lua_State *L) {
+ lua_lock(L);
+ api_checknelems(L, 1);
+ luaG_errormsg(L);
+ /* code unreachable; will unlock when control actually leaves the kernel */
+ return 0; /* to avoid warnings */
+}
+
+
+LUA_API int lua_next (lua_State *L, int idx) {
+ StkId t;
+ int more;
+ lua_lock(L);
+ t = index2addr(L, idx);
+ api_check(ttistable(t), "table expected");
+ more = luaH_next(L, hvalue(t), L->top - 1);
+ if (more) {
+ api_incr_top(L);
+ }
+ else /* no more elements */
+ L->top -= 1; /* remove key */
+ lua_unlock(L);
+ return more;
+}
+
+
+LUA_API void lua_concat (lua_State *L, int n) {
+ lua_lock(L);
+ api_checknelems(L, n);
+ if (n >= 2) {
+ luaC_checkGC(L);
+ luaV_concat(L, n);
+ }
+ else if (n == 0) { /* push empty string */
+ setsvalue2s(L, L->top, luaS_newlstr(L, "", 0));
+ api_incr_top(L);
+ }
+ /* else n == 1; nothing to do */
+ lua_unlock(L);
+}
+
+
+LUA_API void lua_len (lua_State *L, int idx) {
+ StkId t;
+ lua_lock(L);
+ t = index2addr(L, idx);
+ luaV_objlen(L, L->top, t);
+ api_incr_top(L);
+ lua_unlock(L);
+}
+
+
+LUA_API lua_Alloc lua_getallocf (lua_State *L, void **ud) {
+ lua_Alloc f;
+ lua_lock(L);
+ if (ud) *ud = G(L)->ud;
+ f = G(L)->frealloc;
+ lua_unlock(L);
+ return f;
+}
+
+
+LUA_API void lua_setallocf (lua_State *L, lua_Alloc f, void *ud) {
+ lua_lock(L);
+ G(L)->ud = ud;
+ G(L)->frealloc = f;
+ lua_unlock(L);
+}
+
+
+LUA_API void *lua_newuserdata (lua_State *L, size_t size) {
+ Udata *u;
+ lua_lock(L);
+ luaC_checkGC(L);
+ u = luaS_newudata(L, size);
+ setuvalue(L, L->top, u);
+ api_incr_top(L);
+ lua_unlock(L);
+ return getudatamem(u);
+}
+
+
+
+static const char *aux_upvalue (StkId fi, int n, TValue **val,
+ CClosure **owner, UpVal **uv) {
+ switch (ttype(fi)) {
+ case LUA_TCCL: { /* C closure */
+ CClosure *f = clCvalue(fi);
+ if (!(1 <= n && n <= f->nupvalues)) return NULL;
+ *val = &f->upvalue[n-1];
+ if (owner) *owner = f;
+ return "";
+ }
+ case LUA_TLCL: { /* Lua closure */
+ LClosure *f = clLvalue(fi);
+ TString *name;
+ Proto *p = f->p;
+ if (!(1 <= n && n <= p->sizeupvalues)) return NULL;
+ *val = f->upvals[n-1]->v;
+ if (uv) *uv = f->upvals[n - 1];
+ name = p->upvalues[n-1].name;
+ return (name == NULL) ? "(*no name)" : getstr(name);
+ }
+ default: return NULL; /* not a closure */
+ }
+}
+
+
+LUA_API const char *lua_getupvalue (lua_State *L, int funcindex, int n) {
+ const char *name;
+ TValue *val = NULL; /* to avoid warnings */
+ lua_lock(L);
+ name = aux_upvalue(index2addr(L, funcindex), n, &val, NULL, NULL);
+ if (name) {
+ setobj2s(L, L->top, val);
+ api_incr_top(L);
+ }
+ lua_unlock(L);
+ return name;
+}
+
+
+LUA_API const char *lua_setupvalue (lua_State *L, int funcindex, int n) {
+ const char *name;
+ TValue *val = NULL; /* to avoid warnings */
+ CClosure *owner = NULL;
+ UpVal *uv = NULL;
+ StkId fi;
+ lua_lock(L);
+ fi = index2addr(L, funcindex);
+ api_checknelems(L, 1);
+ name = aux_upvalue(fi, n, &val, &owner, &uv);
+ if (name) {
+ L->top--;
+ setobj(L, val, L->top);
+ if (owner) { luaC_barrier(L, owner, L->top); }
+ else if (uv) { luaC_upvalbarrier(L, uv); }
+ }
+ lua_unlock(L);
+ return name;
+}
+
+
+static UpVal **getupvalref (lua_State *L, int fidx, int n, LClosure **pf) {
+ LClosure *f;
+ StkId fi = index2addr(L, fidx);
+ api_check(ttisLclosure(fi), "Lua function expected");
+ f = clLvalue(fi);
+ api_check((1 <= n && n <= f->p->sizeupvalues), "invalid upvalue index");
+ if (pf) *pf = f;
+ return &f->upvals[n - 1]; /* get its upvalue pointer */
+}
+
+
+LUA_API void *lua_upvalueid (lua_State *L, int fidx, int n) {
+ StkId fi = index2addr(L, fidx);
+ switch (ttype(fi)) {
+ case LUA_TLCL: { /* lua closure */
+ return *getupvalref(L, fidx, n, NULL);
+ }
+ case LUA_TCCL: { /* C closure */
+ CClosure *f = clCvalue(fi);
+ api_check(1 <= n && n <= f->nupvalues, "invalid upvalue index");
+ return &f->upvalue[n - 1];
+ }
+ default: {
+ api_check(0, "closure expected");
+ return NULL;
+ }
+ }
+}
+
+
+LUA_API void lua_upvaluejoin (lua_State *L, int fidx1, int n1,
+ int fidx2, int n2) {
+ LClosure *f1;
+ UpVal **up1 = getupvalref(L, fidx1, n1, &f1);
+ UpVal **up2 = getupvalref(L, fidx2, n2, NULL);
+ luaC_upvdeccount(L, *up1);
+ *up1 = *up2;
+ (*up1)->refcount++;
+ if (upisopen(*up1)) (*up1)->u.open.touched = 1;
+ luaC_upvalbarrier(L, *up1);
+}
+
+
diff --git a/src/lapi.h b/src/lapi.h
new file mode 100644
index 0000000000..092f5e974c
--- /dev/null
+++ b/src/lapi.h
@@ -0,0 +1,24 @@
+/*
+** $Id: lapi.h,v 2.8 2014/07/15 21:26:50 roberto Exp $
+** Auxiliary functions from Lua API
+** See Copyright Notice in lua.h
+*/
+
+#ifndef lapi_h
+#define lapi_h
+
+
+#include "llimits.h"
+#include "lstate.h"
+
+#define api_incr_top(L) {L->top++; api_check(L->top <= L->ci->top, \
+ "stack overflow");}
+
+#define adjustresults(L,nres) \
+ { if ((nres) == LUA_MULTRET && L->ci->top < L->top) L->ci->top = L->top; }
+
+#define api_checknelems(L,n) api_check((n) < (L->top - L->ci->func), \
+ "not enough elements in the stack")
+
+
+#endif
diff --git a/lauxlib.c b/src/lauxlib.c
similarity index 51%
rename from lauxlib.c
rename to src/lauxlib.c
index 7cf90cb78a..1c41d6a8ea 100644
--- a/lauxlib.c
+++ b/src/lauxlib.c
@@ -1,5 +1,5 @@
/*
-** $Id: lauxlib.c $
+** $Id: lauxlib.c,v 1.279 2014/12/14 18:32:26 roberto Exp $
** Auxiliary functions for building Lua libraries
** See Copyright Notice in lua.h
*/
@@ -17,15 +17,13 @@
#include
-/*
-** This file uses only the official API of Lua.
+/* This file uses only the official API of Lua.
** Any function declared here could be written as an application function.
*/
#include "lua.h"
#include "lauxlib.h"
-#include "llimits.h"
/*
@@ -35,14 +33,14 @@
*/
-#define LEVELS1 10 /* size of the first part of the stack */
-#define LEVELS2 11 /* size of the second part of the stack */
+#define LEVELS1 12 /* size of the first part of the stack */
+#define LEVELS2 10 /* size of the second part of the stack */
/*
-** Search for 'objidx' in table at index -1. ('objidx' must be an
-** absolute index.) Return 1 + string at top if it found a good name.
+** search for 'objidx' in table at index -1.
+** return 1 + string at top if find a good name.
*/
static int findfield (lua_State *L, int objidx, int level) {
if (level == 0 || !lua_istable(L, -1))
@@ -55,10 +53,10 @@ static int findfield (lua_State *L, int objidx, int level) {
return 1;
}
else if (findfield(L, objidx, level - 1)) { /* try recursively */
- /* stack: lib_name, lib_table, field_name (top) */
- lua_pushliteral(L, "."); /* place '.' between the two names */
- lua_replace(L, -3); /* (in the slot occupied by table) */
- lua_concat(L, 3); /* lib_name.field_name */
+ lua_remove(L, -2); /* remove table (but keep name) */
+ lua_pushliteral(L, ".");
+ lua_insert(L, -2); /* place '.' between the two names */
+ lua_concat(L, 3);
return 1;
}
}
@@ -70,20 +68,20 @@ static int findfield (lua_State *L, int objidx, int level) {
/*
** Search for a name for a function in all loaded modules
+** (registry._LOADED).
*/
static int pushglobalfuncname (lua_State *L, lua_Debug *ar) {
int top = lua_gettop(L);
lua_getinfo(L, "f", ar); /* push function */
- lua_getfield(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE);
- luaL_checkstack(L, 6, "not enough stack"); /* slots for 'findfield' */
+ lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
if (findfield(L, top + 1, 2)) {
const char *name = lua_tostring(L, -1);
- if (strncmp(name, LUA_GNAME ".", 3) == 0) { /* name start with '_G.'? */
+ if (strncmp(name, "_G.", 3) == 0) { /* name start with '_G.'? */
lua_pushstring(L, name + 3); /* push name without prefix */
lua_remove(L, -2); /* remove original name */
}
- lua_copy(L, -1, top + 1); /* copy name to proper place */
- lua_settop(L, top + 1); /* remove table "loaded" and name copy */
+ lua_copy(L, -1, top + 1); /* move name to proper place */
+ lua_pop(L, 2); /* remove pushed values */
return 1;
}
else {
@@ -94,14 +92,14 @@ static int pushglobalfuncname (lua_State *L, lua_Debug *ar) {
static void pushfuncname (lua_State *L, lua_Debug *ar) {
- if (*ar->namewhat != '\0') /* is there a name from code? */
- lua_pushfstring(L, "%s '%s'", ar->namewhat, ar->name); /* use it */
- else if (*ar->what == 'm') /* main? */
- lua_pushliteral(L, "main chunk");
- else if (pushglobalfuncname(L, ar)) { /* try a global name */
+ if (pushglobalfuncname(L, ar)) { /* try first a global name */
lua_pushfstring(L, "function '%s'", lua_tostring(L, -1));
lua_remove(L, -2); /* remove name */
}
+ else if (*ar->namewhat != '\0') /* is there a name from code? */
+ lua_pushfstring(L, "%s '%s'", ar->namewhat, ar->name); /* use it */
+ else if (*ar->what == 'm') /* main? */
+ lua_pushliteral(L, "main chunk");
else if (*ar->what != 'C') /* for Lua functions, use */
lua_pushfstring(L, "function <%s:%d>", ar->short_src, ar->linedefined);
else /* nothing left... */
@@ -109,7 +107,7 @@ static void pushfuncname (lua_State *L, lua_Debug *ar) {
}
-static int lastlevel (lua_State *L) {
+static int countlevels (lua_State *L) {
lua_Debug ar;
int li = 1, le = 1;
/* find an upper bound */
@@ -126,37 +124,30 @@ static int lastlevel (lua_State *L) {
LUALIB_API void luaL_traceback (lua_State *L, lua_State *L1,
const char *msg, int level) {
- luaL_Buffer b;
lua_Debug ar;
- int last = lastlevel(L1);
- int limit2show = (last - level > LEVELS1 + LEVELS2) ? LEVELS1 : -1;
- luaL_buffinit(L, &b);
- if (msg) {
- luaL_addstring(&b, msg);
- luaL_addchar(&b, '\n');
- }
- luaL_addstring(&b, "stack traceback:");
+ int top = lua_gettop(L);
+ int numlevels = countlevels(L1);
+ int mark = (numlevels > LEVELS1 + LEVELS2) ? LEVELS1 : 0;
+ if (msg) lua_pushfstring(L, "%s\n", msg);
+ lua_pushliteral(L, "stack traceback:");
while (lua_getstack(L1, level++, &ar)) {
- if (limit2show-- == 0) { /* too many levels? */
- int n = last - level - LEVELS2 + 1; /* number of levels to skip */
- lua_pushfstring(L, "\n\t...\t(skipping %d levels)", n);
- luaL_addvalue(&b); /* add warning about skip */
- level += n; /* and skip to last levels */
+ if (level == mark) { /* too many levels? */
+ lua_pushliteral(L, "\n\t..."); /* add a '...' */
+ level = numlevels - LEVELS2; /* and skip to last ones */
}
else {
lua_getinfo(L1, "Slnt", &ar);
- if (ar.currentline <= 0)
- lua_pushfstring(L, "\n\t%s: in ", ar.short_src);
- else
- lua_pushfstring(L, "\n\t%s:%d: in ", ar.short_src, ar.currentline);
- luaL_addvalue(&b);
+ lua_pushfstring(L, "\n\t%s:", ar.short_src);
+ if (ar.currentline > 0)
+ lua_pushfstring(L, "%d:", ar.currentline);
+ lua_pushliteral(L, " in ");
pushfuncname(L, &ar);
- luaL_addvalue(&b);
if (ar.istailcall)
- luaL_addstring(&b, "\n\t(...tail calls...)");
+ lua_pushliteral(L, "\n\t(...tail calls...)");
+ lua_concat(L, lua_gettop(L) - top);
}
}
- luaL_pushresult(&b);
+ lua_concat(L, lua_gettop(L) - top);
}
/* }====================================================== */
@@ -170,31 +161,23 @@ LUALIB_API void luaL_traceback (lua_State *L, lua_State *L1,
LUALIB_API int luaL_argerror (lua_State *L, int arg, const char *extramsg) {
lua_Debug ar;
- const char *argword;
if (!lua_getstack(L, 0, &ar)) /* no stack frame? */
return luaL_error(L, "bad argument #%d (%s)", arg, extramsg);
- lua_getinfo(L, "nt", &ar);
- if (arg <= ar.extraargs) /* error in an extra argument? */
- argword = "extra argument";
- else {
- arg -= ar.extraargs; /* do not count extra arguments */
- if (strcmp(ar.namewhat, "method") == 0) { /* colon syntax? */
- arg--; /* do not count (extra) self argument */
- if (arg == 0) /* error in self argument? */
- return luaL_error(L, "calling '%s' on bad self (%s)",
- ar.name, extramsg);
- /* else go through; error in a regular argument */
- }
- argword = "argument";
+ lua_getinfo(L, "n", &ar);
+ if (strcmp(ar.namewhat, "method") == 0) {
+ arg--; /* do not count 'self' */
+ if (arg == 0) /* error is in the self argument itself? */
+ return luaL_error(L, "calling '%s' on bad self (%s)",
+ ar.name, extramsg);
}
if (ar.name == NULL)
ar.name = (pushglobalfuncname(L, &ar)) ? lua_tostring(L, -1) : "?";
- return luaL_error(L, "bad %s #%d to '%s' (%s)",
- argword, arg, ar.name, extramsg);
+ return luaL_error(L, "bad argument #%d to '%s' (%s)",
+ arg, ar.name, extramsg);
}
-LUALIB_API int luaL_typeerror (lua_State *L, int arg, const char *tname) {
+static int typeerror (lua_State *L, int arg, const char *tname) {
const char *msg;
const char *typearg; /* name for the type of the actual argument */
if (luaL_getmetafield(L, arg, "__name") == LUA_TSTRING)
@@ -209,14 +192,10 @@ LUALIB_API int luaL_typeerror (lua_State *L, int arg, const char *tname) {
static void tag_error (lua_State *L, int arg, int tag) {
- luaL_typeerror(L, arg, lua_typename(L, tag));
+ typeerror(L, arg, lua_typename(L, tag));
}
-/*
-** The use of 'lua_pushfstring' ensures this function does not
-** need reserved stack space when called.
-*/
LUALIB_API void luaL_where (lua_State *L, int level) {
lua_Debug ar;
if (lua_getstack(L, level, &ar)) { /* check function at level */
@@ -226,15 +205,10 @@ LUALIB_API void luaL_where (lua_State *L, int level) {
return;
}
}
- lua_pushfstring(L, ""); /* else, no information available... */
+ lua_pushliteral(L, ""); /* else, no information available... */
}
-/*
-** Again, the use of 'lua_pushvfstring' ensures this function does
-** not need reserved stack space when called. (At worst, it generates
-** a memory error instead of the given message.)
-*/
LUALIB_API int luaL_error (lua_State *L, const char *fmt, ...) {
va_list argp;
va_start(argp, fmt);
@@ -253,13 +227,11 @@ LUALIB_API int luaL_fileresult (lua_State *L, int stat, const char *fname) {
return 1;
}
else {
- const char *msg;
- luaL_pushfail(L);
- msg = (en != 0) ? strerror(en) : "(no extra info)";
+ lua_pushnil(L);
if (fname)
- lua_pushfstring(L, "%s: %s", fname, msg);
+ lua_pushfstring(L, "%s: %s", fname, strerror(en));
else
- lua_pushstring(L, msg);
+ lua_pushstring(L, strerror(en));
lua_pushinteger(L, en);
return 3;
}
@@ -289,25 +261,24 @@ LUALIB_API int luaL_fileresult (lua_State *L, int stat, const char *fname) {
LUALIB_API int luaL_execresult (lua_State *L, int stat) {
- if (stat != 0 && errno != 0) /* error with an 'errno'? */
+ const char *what = "exit"; /* type of termination */
+ if (stat == -1) /* error? */
return luaL_fileresult(L, 0, NULL);
else {
- const char *what = "exit"; /* type of termination */
l_inspectstat(stat, what); /* interpret result */
if (*what == 'e' && stat == 0) /* successful termination? */
lua_pushboolean(L, 1);
else
- luaL_pushfail(L);
+ lua_pushnil(L);
lua_pushstring(L, what);
lua_pushinteger(L, stat);
- return 3; /* return true/fail,what,code */
+ return 3; /* return true/nil,what,code */
}
}
/* }====================================================== */
-
/*
** {======================================================
** Userdata's metatable manipulation
@@ -315,10 +286,10 @@ LUALIB_API int luaL_execresult (lua_State *L, int stat) {
*/
LUALIB_API int luaL_newmetatable (lua_State *L, const char *tname) {
- if (luaL_getmetatable(L, tname) != LUA_TNIL) /* name already in use? */
+ if (luaL_getmetatable(L, tname)) /* name already in use? */
return 0; /* leave previous value on top, but return 0 */
lua_pop(L, 1);
- lua_createtable(L, 0, 2); /* create metatable */
+ lua_newtable(L); /* create metatable */
lua_pushstring(L, tname);
lua_setfield(L, -2, "__name"); /* metatable.__name = tname */
lua_pushvalue(L, -1);
@@ -350,7 +321,7 @@ LUALIB_API void *luaL_testudata (lua_State *L, int ud, const char *tname) {
LUALIB_API void *luaL_checkudata (lua_State *L, int ud, const char *tname) {
void *p = luaL_testudata(L, ud, tname);
- luaL_argexpected(L, p != NULL, ud, tname);
+ if (p == NULL) typeerror(L, ud, tname);
return p;
}
@@ -376,15 +347,10 @@ LUALIB_API int luaL_checkoption (lua_State *L, int arg, const char *def,
}
-/*
-** Ensures the stack has at least 'space' extra slots, raising an error
-** if it cannot fulfill the request. (The error handling needs a few
-** extra slots to format the error message. In case of an error without
-** this extra space, Lua will generate the same 'stack overflow' error,
-** but without 'msg'.)
-*/
LUALIB_API void luaL_checkstack (lua_State *L, int space, const char *msg) {
- if (l_unlikely(!lua_checkstack(L, space))) {
+ /* keep some extra space to run error routines, if needed */
+ const int extra = LUA_MINSTACK;
+ if (!lua_checkstack(L, space + extra)) {
if (msg)
luaL_error(L, "stack overflow (%s)", msg);
else
@@ -394,20 +360,20 @@ LUALIB_API void luaL_checkstack (lua_State *L, int space, const char *msg) {
LUALIB_API void luaL_checktype (lua_State *L, int arg, int t) {
- if (l_unlikely(lua_type(L, arg) != t))
+ if (lua_type(L, arg) != t)
tag_error(L, arg, t);
}
LUALIB_API void luaL_checkany (lua_State *L, int arg) {
- if (l_unlikely(lua_type(L, arg) == LUA_TNONE))
+ if (lua_type(L, arg) == LUA_TNONE)
luaL_argerror(L, arg, "value expected");
}
LUALIB_API const char *luaL_checklstring (lua_State *L, int arg, size_t *len) {
const char *s = lua_tolstring(L, arg, len);
- if (l_unlikely(!s)) tag_error(L, arg, LUA_TSTRING);
+ if (!s) tag_error(L, arg, LUA_TSTRING);
return s;
}
@@ -426,7 +392,7 @@ LUALIB_API const char *luaL_optlstring (lua_State *L, int arg,
LUALIB_API lua_Number luaL_checknumber (lua_State *L, int arg) {
int isnum;
lua_Number d = lua_tonumberx(L, arg, &isnum);
- if (l_unlikely(!isnum))
+ if (!isnum)
tag_error(L, arg, LUA_TNUMBER);
return d;
}
@@ -448,7 +414,7 @@ static void interror (lua_State *L, int arg) {
LUALIB_API lua_Integer luaL_checkinteger (lua_State *L, int arg) {
int isnum;
lua_Integer d = lua_tointegerx(L, arg, &isnum);
- if (l_unlikely(!isnum)) {
+ if (!isnum) {
interror(L, arg);
}
return d;
@@ -469,137 +435,42 @@ LUALIB_API lua_Integer luaL_optinteger (lua_State *L, int arg,
** =======================================================
*/
-/* userdata to box arbitrary data */
-typedef struct UBox {
- void *box;
- size_t bsize;
-} UBox;
-
-
-/* Resize the buffer used by a box. Optimize for the common case of
-** resizing to the old size. (For instance, __gc will resize the box
-** to 0 even after it was closed. 'pushresult' may also resize it to a
-** final size that is equal to the one set when the buffer was created.)
-*/
-static void *resizebox (lua_State *L, int idx, size_t newsize) {
- UBox *box = (UBox *)lua_touserdata(L, idx);
- if (box->bsize == newsize) /* not changing size? */
- return box->box; /* keep the buffer */
- else {
- void *ud;
- lua_Alloc allocf = lua_getallocf(L, &ud);
- void *temp = allocf(ud, box->box, box->bsize, newsize);
- if (l_unlikely(temp == NULL && newsize > 0)) { /* allocation error? */
- lua_pushliteral(L, "not enough memory");
- lua_error(L); /* raise a memory error */
- }
- box->box = temp;
- box->bsize = newsize;
- return temp;
- }
-}
-
-
-static int boxgc (lua_State *L) {
- resizebox(L, 1, 0);
- return 0;
-}
-
-
-static const luaL_Reg boxmt[] = { /* box metamethods */
- {"__gc", boxgc},
- {"__close", boxgc},
- {NULL, NULL}
-};
-
-
-static void newbox (lua_State *L) {
- UBox *box = (UBox *)lua_newuserdatauv(L, sizeof(UBox), 0);
- box->box = NULL;
- box->bsize = 0;
- if (luaL_newmetatable(L, "_UBOX*")) /* creating metatable? */
- luaL_setfuncs(L, boxmt, 0); /* set its metamethods */
- lua_setmetatable(L, -2);
-}
-
-
/*
** check whether buffer is using a userdata on the stack as a temporary
** buffer
*/
-#define buffonstack(B) ((B)->b != (B)->init.b)
-
-
-/*
-** Whenever buffer is accessed, slot 'idx' must either be a box (which
-** cannot be NULL) or it is a placeholder for the buffer.
-*/
-#define checkbufferlevel(B,idx) \
- lua_assert(buffonstack(B) ? lua_touserdata(B->L, idx) != NULL \
- : lua_touserdata(B->L, idx) == (void*)B)
-
-
-/*
-** Compute new size for buffer 'B', enough to accommodate extra 'sz'
-** bytes plus one for a terminating zero.
-*/
-static size_t newbuffsize (luaL_Buffer *B, size_t sz) {
- size_t newsize = B->size;
- if (l_unlikely(sz >= MAX_SIZE - B->n))
- return cast_sizet(luaL_error(B->L, "resulting string too large"));
- /* else B->n + sz + 1 <= MAX_SIZE */
- if (newsize <= MAX_SIZE/3 * 2) /* no overflow? */
- newsize += (newsize >> 1); /* new size *= 1.5 */
- if (newsize < B->n + sz + 1) /* not big enough? */
- newsize = B->n + sz + 1;
- return newsize;
-}
+#define buffonstack(B) ((B)->b != (B)->initb)
/*
-** Returns a pointer to a free area with at least 'sz' bytes in buffer
-** 'B'. 'boxidx' is the relative position in the stack where is the
-** buffer's box or its placeholder.
+** returns a pointer to a free area with at least 'sz' bytes
*/
-static char *prepbuffsize (luaL_Buffer *B, size_t sz, int boxidx) {
- checkbufferlevel(B, boxidx);
- if (B->size - B->n >= sz) /* enough space? */
- return B->b + B->n;
- else {
- lua_State *L = B->L;
+LUALIB_API char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz) {
+ lua_State *L = B->L;
+ if (B->size - B->n < sz) { /* not enough space? */
char *newbuff;
- size_t newsize = newbuffsize(B, sz);
+ size_t newsize = B->size * 2; /* double buffer size */
+ if (newsize - B->n < sz) /* not big enough? */
+ newsize = B->n + sz;
+ if (newsize < B->n || newsize - B->n < sz)
+ luaL_error(L, "buffer too large");
/* create larger buffer */
- if (buffonstack(B)) /* buffer already has a box? */
- newbuff = (char *)resizebox(L, boxidx, newsize); /* resize it */
- else { /* no box yet */
- lua_remove(L, boxidx); /* remove placeholder */
- newbox(L); /* create a new box */
- lua_insert(L, boxidx); /* move box to its intended position */
- lua_toclose(L, boxidx);
- newbuff = (char *)resizebox(L, boxidx, newsize);
- memcpy(newbuff, B->b, B->n * sizeof(char)); /* copy original content */
- }
+ newbuff = (char *)lua_newuserdata(L, newsize * sizeof(char));
+ /* move content to new buffer */
+ memcpy(newbuff, B->b, B->n * sizeof(char));
+ if (buffonstack(B))
+ lua_remove(L, -2); /* remove old buffer */
B->b = newbuff;
B->size = newsize;
- return newbuff + B->n;
}
-}
-
-/*
-** returns a pointer to a free area with at least 'sz' bytes
-*/
-LUALIB_API char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz) {
- return prepbuffsize(B, sz, -1);
+ return &B->b[B->n];
}
LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) {
- if (l > 0) { /* avoid 'memcpy' when 's' can be NULL */
- char *b = prepbuffsize(B, l, -1);
- memcpy(b, s, l * sizeof(char));
- luaL_addsize(B, l);
- }
+ char *b = luaL_prepbuffsize(B, l);
+ memcpy(b, s, l * sizeof(char));
+ luaL_addsize(B, l);
}
@@ -610,25 +481,9 @@ LUALIB_API void luaL_addstring (luaL_Buffer *B, const char *s) {
LUALIB_API void luaL_pushresult (luaL_Buffer *B) {
lua_State *L = B->L;
- checkbufferlevel(B, -1);
- if (!buffonstack(B)) /* using static buffer? */
- lua_pushlstring(L, B->b, B->n); /* save result as regular string */
- else { /* reuse buffer already allocated */
- UBox *box = (UBox *)lua_touserdata(L, -1);
- void *ud;
- lua_Alloc allocf = lua_getallocf(L, &ud); /* function to free buffer */
- size_t len = B->n; /* final string length */
- char *s;
- resizebox(L, -1, len + 1); /* adjust box size to content size */
- s = (char*)box->box; /* final buffer address */
- s[len] = '\0'; /* add ending zero */
- /* clear box, as Lua will take control of the buffer */
- box->bsize = 0; box->box = NULL;
- lua_pushexternalstring(L, s, len, allocf, ud);
- lua_closeslot(L, -2); /* close the box */
- lua_gc(L, LUA_GCSTEP, len);
- }
- lua_remove(L, -2); /* remove box or placeholder from the stack */
+ lua_pushlstring(L, B->b, B->n);
+ if (buffonstack(B))
+ lua_remove(L, -2); /* remove old buffer */
}
@@ -638,38 +493,28 @@ LUALIB_API void luaL_pushresultsize (luaL_Buffer *B, size_t sz) {
}
-/*
-** 'luaL_addvalue' is the only function in the Buffer system where the
-** box (if existent) is not on the top of the stack. So, instead of
-** calling 'luaL_addlstring', it replicates the code using -2 as the
-** last argument to 'prepbuffsize', signaling that the box is (or will
-** be) below the string being added to the buffer. (Box creation can
-** trigger an emergency GC, so we should not remove the string from the
-** stack before we have the space guaranteed.)
-*/
LUALIB_API void luaL_addvalue (luaL_Buffer *B) {
lua_State *L = B->L;
- size_t len;
- const char *s = lua_tolstring(L, -1, &len);
- char *b = prepbuffsize(B, len, -2);
- memcpy(b, s, len * sizeof(char));
- luaL_addsize(B, len);
- lua_pop(L, 1); /* pop string */
+ size_t l;
+ const char *s = lua_tolstring(L, -1, &l);
+ if (buffonstack(B))
+ lua_insert(L, -2); /* put value below buffer */
+ luaL_addlstring(B, s, l);
+ lua_remove(L, (buffonstack(B)) ? -2 : -1); /* remove value */
}
LUALIB_API void luaL_buffinit (lua_State *L, luaL_Buffer *B) {
B->L = L;
- B->b = B->init.b;
+ B->b = B->initb;
B->n = 0;
B->size = LUAL_BUFFERSIZE;
- lua_pushlightuserdata(L, (void*)B); /* push placeholder */
}
LUALIB_API char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz) {
luaL_buffinit(L, B);
- return prepbuffsize(B, sz, -1);
+ return luaL_prepbuffsize(B, sz);
}
/* }====================================================== */
@@ -681,11 +526,10 @@ LUALIB_API char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz) {
** =======================================================
*/
-/*
-** The previously freed references form a linked list: t[1] is the index
-** of a first free index, t[t[1]] is the index of the second element,
-** etc. A zero signals the end of the list.
-*/
+/* index of free-list header */
+#define freelist 0
+
+
LUALIB_API int luaL_ref (lua_State *L, int t) {
int ref;
if (lua_isnil(L, -1)) {
@@ -693,18 +537,12 @@ LUALIB_API int luaL_ref (lua_State *L, int t) {
return LUA_REFNIL; /* 'nil' has a unique fixed reference */
}
t = lua_absindex(L, t);
- if (lua_rawgeti(L, t, 1) == LUA_TNUMBER) /* already initialized? */
- ref = (int)lua_tointeger(L, -1); /* ref = t[1] */
- else { /* first access */
- lua_assert(!lua_toboolean(L, -1)); /* must be nil or false */
- ref = 0; /* list is empty */
- lua_pushinteger(L, 0); /* initialize as an empty list */
- lua_rawseti(L, t, 1); /* ref = t[1] = 0 */
- }
- lua_pop(L, 1); /* remove element from stack */
+ lua_rawgeti(L, t, freelist); /* get first free element */
+ ref = (int)lua_tointeger(L, -1); /* ref = t[freelist] */
+ lua_pop(L, 1); /* remove it from stack */
if (ref != 0) { /* any free element? */
lua_rawgeti(L, t, ref); /* remove it from list */
- lua_rawseti(L, t, 1); /* (t[1] = t[ref]) */
+ lua_rawseti(L, t, freelist); /* (t[freelist] = t[ref]) */
}
else /* no free elements */
ref = (int)lua_rawlen(L, t) + 1; /* get a new reference */
@@ -716,11 +554,10 @@ LUALIB_API int luaL_ref (lua_State *L, int t) {
LUALIB_API void luaL_unref (lua_State *L, int t, int ref) {
if (ref >= 0) {
t = lua_absindex(L, t);
- lua_rawgeti(L, t, 1);
- lua_assert(lua_isinteger(L, -1));
- lua_rawseti(L, t, ref); /* t[ref] = t[1] */
+ lua_rawgeti(L, t, freelist);
+ lua_rawseti(L, t, ref); /* t[ref] = t[freelist] */
lua_pushinteger(L, ref);
- lua_rawseti(L, t, 1); /* t[1] = ref */
+ lua_rawseti(L, t, freelist); /* t[freelist] = ref */
}
}
@@ -734,7 +571,7 @@ LUALIB_API void luaL_unref (lua_State *L, int t, int ref) {
*/
typedef struct LoadF {
- unsigned n; /* number of pre-read characters */
+ int n; /* number of pre-read characters */
FILE *f; /* file being read */
char buff[BUFSIZ]; /* area for reading file */
} LoadF;
@@ -742,7 +579,7 @@ typedef struct LoadF {
static const char *getF (lua_State *L, void *ud, size_t *size) {
LoadF *lf = (LoadF *)ud;
- UNUSED(L);
+ (void)L; /* not used */
if (lf->n > 0) { /* are there pre-read characters to be read? */
*size = lf->n; /* return them (chars already in buffer) */
lf->n = 0; /* no more pre-read characters */
@@ -759,29 +596,25 @@ static const char *getF (lua_State *L, void *ud, size_t *size) {
static int errfile (lua_State *L, const char *what, int fnameindex) {
- int err = errno;
+ const char *serr = strerror(errno);
const char *filename = lua_tostring(L, fnameindex) + 1;
- if (err != 0)
- lua_pushfstring(L, "cannot %s %s: %s", what, filename, strerror(err));
- else
- lua_pushfstring(L, "cannot %s %s", what, filename);
+ lua_pushfstring(L, "cannot %s %s: %s", what, filename, serr);
lua_remove(L, fnameindex);
return LUA_ERRFILE;
}
-/*
-** Skip an optional BOM at the start of a stream. If there is an
-** incomplete BOM (the first character is correct but the rest is
-** not), returns the first character anyway to force an error
-** (as no chunk can start with 0xEF).
-*/
-static int skipBOM (FILE *f) {
- int c = getc(f); /* read first character */
- if (c == 0xEF && getc(f) == 0xBB && getc(f) == 0xBF) /* correct BOM? */
- return getc(f); /* ignore BOM and return next char */
- else /* no (valid) BOM */
- return c; /* return first character */
+static int skipBOM (LoadF *lf) {
+ const char *p = "\xEF\xBB\xBF"; /* Utf8 BOM mark */
+ int c;
+ lf->n = 0;
+ do {
+ c = getc(lf->f);
+ if (c == EOF || c != *(const unsigned char *)p++) return c;
+ lf->buff[lf->n++] = c; /* to be read by the parser */
+ } while (*p != '\0');
+ lf->n = 0; /* prefix matched; discard it */
+ return getc(lf->f); /* return next character */
}
@@ -792,13 +625,13 @@ static int skipBOM (FILE *f) {
** first "valid" character of the file (after the optional BOM and
** a first-line comment).
*/
-static int skipcomment (FILE *f, int *cp) {
- int c = *cp = skipBOM(f);
+static int skipcomment (LoadF *lf, int *cp) {
+ int c = *cp = skipBOM(lf);
if (c == '#') { /* first line is a comment (Unix exec. file)? */
do { /* skip first line */
- c = getc(f);
- } while (c != EOF && c != '\n');
- *cp = getc(f); /* next character after comment, if present */
+ c = getc(lf->f);
+ } while (c != EOF && c != '\n') ;
+ *cp = getc(lf->f); /* skip end-of-line, if present */
return 1; /* there was a comment */
}
else return 0; /* no comment */
@@ -817,27 +650,20 @@ LUALIB_API int luaL_loadfilex (lua_State *L, const char *filename,
}
else {
lua_pushfstring(L, "@%s", filename);
- errno = 0;
lf.f = fopen(filename, "r");
if (lf.f == NULL) return errfile(L, "open", fnameindex);
}
- lf.n = 0;
- if (skipcomment(lf.f, &c)) /* read initial portion */
- lf.buff[lf.n++] = '\n'; /* add newline to correct line numbers */
- if (c == LUA_SIGNATURE[0]) { /* binary file? */
- lf.n = 0; /* remove possible newline */
- if (filename) { /* "real" file? */
- errno = 0;
- lf.f = freopen(filename, "rb", lf.f); /* reopen in binary mode */
- if (lf.f == NULL) return errfile(L, "reopen", fnameindex);
- skipcomment(lf.f, &c); /* re-read initial portion */
- }
+ if (skipcomment(&lf, &c)) /* read initial portion */
+ lf.buff[lf.n++] = '\n'; /* add line to correct line numbers */
+ if (c == LUA_SIGNATURE[0] && filename) { /* binary file? */
+ lf.f = freopen(filename, "rb", lf.f); /* reopen in binary mode */
+ if (lf.f == NULL) return errfile(L, "reopen", fnameindex);
+ skipcomment(&lf, &c); /* re-read initial portion */
}
if (c != EOF)
- lf.buff[lf.n++] = cast_char(c); /* 'c' is the first character */
+ lf.buff[lf.n++] = c; /* 'c' is the first character of the stream */
status = lua_load(L, getF, &lf, lua_tostring(L, -1), mode);
readstatus = ferror(lf.f);
- errno = 0; /* no useful error number until here */
if (filename) fclose(lf.f); /* close file (even in case of errors) */
if (readstatus) {
lua_settop(L, fnameindex); /* ignore results from 'lua_load' */
@@ -856,7 +682,7 @@ typedef struct LoadS {
static const char *getS (lua_State *L, void *ud, size_t *size) {
LoadS *ls = (LoadS *)ud;
- UNUSED(L);
+ (void)L; /* not used */
if (ls->size == 0) return NULL;
*size = ls->size;
ls->size = 0;
@@ -912,7 +738,7 @@ LUALIB_API lua_Integer luaL_len (lua_State *L, int idx) {
int isnum;
lua_len(L, idx);
l = lua_tointegerx(L, -1, &isnum);
- if (l_unlikely(!isnum))
+ if (!isnum)
luaL_error(L, "object length is not an integer");
lua_pop(L, 1); /* remove object */
return l;
@@ -920,17 +746,13 @@ LUALIB_API lua_Integer luaL_len (lua_State *L, int idx) {
LUALIB_API const char *luaL_tolstring (lua_State *L, int idx, size_t *len) {
- idx = lua_absindex(L,idx);
- if (luaL_callmeta(L, idx, "__tostring")) { /* metafield? */
- if (!lua_isstring(L, -1))
- luaL_error(L, "'__tostring' must return a string");
- }
- else {
+ if (!luaL_callmeta(L, idx, "__tostring")) { /* no metafield? */
switch (lua_type(L, idx)) {
case LUA_TNUMBER: {
- char buff[LUA_N2SBUFFSZ];
- lua_numbertocstring(L, idx, buff);
- lua_pushstring(L, buff);
+ if (lua_isinteger(L, idx))
+ lua_pushfstring(L, "%I", lua_tointeger(L, idx));
+ else
+ lua_pushfstring(L, "%f", lua_tonumber(L, idx));
break;
}
case LUA_TSTRING:
@@ -942,21 +764,97 @@ LUALIB_API const char *luaL_tolstring (lua_State *L, int idx, size_t *len) {
case LUA_TNIL:
lua_pushliteral(L, "nil");
break;
- default: {
- int tt = luaL_getmetafield(L, idx, "__name"); /* try name */
- const char *kind = (tt == LUA_TSTRING) ? lua_tostring(L, -1) :
- luaL_typename(L, idx);
- lua_pushfstring(L, "%s: %p", kind, lua_topointer(L, idx));
- if (tt != LUA_TNIL)
- lua_remove(L, -2); /* remove '__name' */
+ default:
+ lua_pushfstring(L, "%s: %p", luaL_typename(L, idx),
+ lua_topointer(L, idx));
break;
- }
}
}
return lua_tolstring(L, -1, len);
}
+/*
+** {======================================================
+** Compatibility with 5.1 module functions
+** =======================================================
+*/
+#if defined(LUA_COMPAT_MODULE)
+
+static const char *luaL_findtable (lua_State *L, int idx,
+ const char *fname, int szhint) {
+ const char *e;
+ if (idx) lua_pushvalue(L, idx);
+ do {
+ e = strchr(fname, '.');
+ if (e == NULL) e = fname + strlen(fname);
+ lua_pushlstring(L, fname, e - fname);
+ if (lua_rawget(L, -2) == LUA_TNIL) { /* no such field? */
+ lua_pop(L, 1); /* remove this nil */
+ lua_createtable(L, 0, (*e == '.' ? 1 : szhint)); /* new table for field */
+ lua_pushlstring(L, fname, e - fname);
+ lua_pushvalue(L, -2);
+ lua_settable(L, -4); /* set new table into field */
+ }
+ else if (!lua_istable(L, -1)) { /* field has a non-table value? */
+ lua_pop(L, 2); /* remove table and value */
+ return fname; /* return problematic part of the name */
+ }
+ lua_remove(L, -2); /* remove previous table */
+ fname = e + 1;
+ } while (*e == '.');
+ return NULL;
+}
+
+
+/*
+** Count number of elements in a luaL_Reg list.
+*/
+static int libsize (const luaL_Reg *l) {
+ int size = 0;
+ for (; l && l->name; l++) size++;
+ return size;
+}
+
+
+/*
+** Find or create a module table with a given name. The function
+** first looks at the _LOADED table and, if that fails, try a
+** global variable with that name. In any case, leaves on the stack
+** the module table.
+*/
+LUALIB_API void luaL_pushmodule (lua_State *L, const char *modname,
+ int sizehint) {
+ luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED", 1); /* get _LOADED table */
+ if (lua_getfield(L, -1, modname) != LUA_TTABLE) { /* no _LOADED[modname]? */
+ lua_pop(L, 1); /* remove previous result */
+ /* try global variable (and create one if it does not exist) */
+ lua_pushglobaltable(L);
+ if (luaL_findtable(L, 0, modname, sizehint) != NULL)
+ luaL_error(L, "name conflict for module '%s'", modname);
+ lua_pushvalue(L, -1);
+ lua_setfield(L, -3, modname); /* _LOADED[modname] = new table */
+ }
+ lua_remove(L, -2); /* remove _LOADED table */
+}
+
+
+LUALIB_API void luaL_openlib (lua_State *L, const char *libname,
+ const luaL_Reg *l, int nup) {
+ luaL_checkversion(L);
+ if (libname) {
+ luaL_pushmodule(L, libname, libsize(l)); /* get/create library table */
+ lua_insert(L, -(nup + 1)); /* move library table to below upvalues */
+ }
+ if (l)
+ luaL_setfuncs(L, l, nup);
+ else
+ lua_pop(L, nup); /* remove upvalues */
+}
+
+#endif
+/* }====================================================== */
+
/*
** set functions from list 'l' into table at top - 'nup'; each
** function gets the 'nup' elements at the top as upvalues.
@@ -965,14 +863,10 @@ LUALIB_API const char *luaL_tolstring (lua_State *L, int idx, size_t *len) {
LUALIB_API void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup) {
luaL_checkstack(L, nup, "too many upvalues");
for (; l->name != NULL; l++) { /* fill the table with given functions */
- if (l->func == NULL) /* placeholder? */
- lua_pushboolean(L, 0);
- else {
- int i;
- for (i = 0; i < nup; i++) /* copy upvalues to the top */
- lua_pushvalue(L, -nup);
- lua_pushcclosure(L, l->func, nup); /* closure with those upvalues */
- }
+ int i;
+ for (i = 0; i < nup; i++) /* copy upvalues to the top */
+ lua_pushvalue(L, -nup);
+ lua_pushcclosure(L, l->func, nup); /* closure with those upvalues */
lua_setfield(L, -(nup + 2), l->name);
}
lua_pop(L, nup); /* remove upvalues */
@@ -1005,17 +899,17 @@ LUALIB_API int luaL_getsubtable (lua_State *L, int idx, const char *fname) {
*/
LUALIB_API void luaL_requiref (lua_State *L, const char *modname,
lua_CFunction openf, int glb) {
- luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE);
- lua_getfield(L, -1, modname); /* LOADED[modname] */
+ luaL_getsubtable(L, LUA_REGISTRYINDEX, "_LOADED");
+ lua_getfield(L, -1, modname); /* _LOADED[modname] */
if (!lua_toboolean(L, -1)) { /* package not already loaded? */
lua_pop(L, 1); /* remove field */
lua_pushcfunction(L, openf);
lua_pushstring(L, modname); /* argument to open function */
lua_call(L, 1, 1); /* call 'openf' to open module */
lua_pushvalue(L, -1); /* make copy of module (call result) */
- lua_setfield(L, -3, modname); /* LOADED[modname] = module */
+ lua_setfield(L, -3, modname); /* _LOADED[modname] = module */
}
- lua_remove(L, -2); /* remove LOADED table */
+ lua_remove(L, -2); /* remove _LOADED table */
if (glb) {
lua_pushvalue(L, -1); /* copy of module */
lua_setglobal(L, modname); /* _G[modname] = module */
@@ -1023,31 +917,25 @@ LUALIB_API void luaL_requiref (lua_State *L, const char *modname,
}
-LUALIB_API void luaL_addgsub (luaL_Buffer *b, const char *s,
- const char *p, const char *r) {
+LUALIB_API const char *luaL_gsub (lua_State *L, const char *s, const char *p,
+ const char *r) {
const char *wild;
size_t l = strlen(p);
+ luaL_Buffer b;
+ luaL_buffinit(L, &b);
while ((wild = strstr(s, p)) != NULL) {
- luaL_addlstring(b, s, ct_diff2sz(wild - s)); /* push prefix */
- luaL_addstring(b, r); /* push replacement in place of pattern */
+ luaL_addlstring(&b, s, wild - s); /* push prefix */
+ luaL_addstring(&b, r); /* push replacement in place of pattern */
s = wild + l; /* continue after 'p' */
}
- luaL_addstring(b, s); /* push last suffix */
-}
-
-
-LUALIB_API const char *luaL_gsub (lua_State *L, const char *s,
- const char *p, const char *r) {
- luaL_Buffer b;
- luaL_buffinit(L, &b);
- luaL_addgsub(&b, s, p, r);
+ luaL_addstring(&b, s); /* push last suffix */
luaL_pushresult(&b);
return lua_tostring(L, -1);
}
-void *luaL_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
- UNUSED(ud); UNUSED(osize);
+static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
+ (void)ud; (void)osize; /* not used */
if (nsize == 0) {
free(ptr);
return NULL;
@@ -1057,146 +945,28 @@ void *luaL_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
}
-/*
-** Standard panic function just prints an error message. The test
-** with 'lua_type' avoids possible memory errors in 'lua_tostring'.
-*/
static int panic (lua_State *L) {
- const char *msg = (lua_type(L, -1) == LUA_TSTRING)
- ? lua_tostring(L, -1)
- : "error object is not a string";
lua_writestringerror("PANIC: unprotected error in call to Lua API (%s)\n",
- msg);
+ lua_tostring(L, -1));
return 0; /* return to Lua to abort */
}
-/*
-** Warning functions:
-** warnfoff: warning system is off
-** warnfon: ready to start a new message
-** warnfcont: previous message is to be continued
-*/
-static void warnfoff (void *ud, const char *message, int tocont);
-static void warnfon (void *ud, const char *message, int tocont);
-static void warnfcont (void *ud, const char *message, int tocont);
-
-
-/*
-** Check whether message is a control message. If so, execute the
-** control or ignore it if unknown.
-*/
-static int checkcontrol (lua_State *L, const char *message, int tocont) {
- if (tocont || *(message++) != '@') /* not a control message? */
- return 0;
- else {
- if (strcmp(message, "off") == 0)
- lua_setwarnf(L, warnfoff, L); /* turn warnings off */
- else if (strcmp(message, "on") == 0)
- lua_setwarnf(L, warnfon, L); /* turn warnings on */
- return 1; /* it was a control message */
- }
-}
-
-
-static void warnfoff (void *ud, const char *message, int tocont) {
- checkcontrol((lua_State *)ud, message, tocont);
-}
-
-
-/*
-** Writes the message and handle 'tocont', finishing the message
-** if needed and setting the next warn function.
-*/
-static void warnfcont (void *ud, const char *message, int tocont) {
- lua_State *L = (lua_State *)ud;
- lua_writestringerror("%s", message); /* write message */
- if (tocont) /* not the last part? */
- lua_setwarnf(L, warnfcont, L); /* to be continued */
- else { /* last part */
- lua_writestringerror("%s", "\n"); /* finish message with end-of-line */
- lua_setwarnf(L, warnfon, L); /* next call is a new message */
- }
-}
-
-
-static void warnfon (void *ud, const char *message, int tocont) {
- if (checkcontrol((lua_State *)ud, message, tocont)) /* control message? */
- return; /* nothing else to be done */
- lua_writestringerror("%s", "Lua warning: "); /* start a new warning */
- warnfcont(ud, message, tocont); /* finish processing */
-}
-
-
-
-/*
-** A function to compute an unsigned int with some level of
-** randomness. Rely on Address Space Layout Randomization (if present)
-** and the current time.
-*/
-#if !defined(luai_makeseed)
-
-#include
-
-
-/* Size for the buffer, in bytes */
-#define BUFSEEDB (sizeof(void*) + sizeof(time_t))
-
-/* Size for the buffer in int's, rounded up */
-#define BUFSEED ((BUFSEEDB + sizeof(int) - 1) / sizeof(int))
-
-/*
-** Copy the contents of variable 'v' into the buffer pointed by 'b'.
-** (The '&b[0]' disguises 'b' to fix an absurd warning from clang.)
-*/
-#define addbuff(b,v) (memcpy(&b[0], &(v), sizeof(v)), b += sizeof(v))
-
-
-static unsigned int luai_makeseed (void) {
- unsigned int buff[BUFSEED];
- unsigned int res;
- unsigned int i;
- time_t t = time(NULL);
- char *b = (char*)buff;
- addbuff(b, b); /* local variable's address */
- addbuff(b, t); /* time */
- /* fill (rare but possible) remain of the buffer with zeros */
- memset(b, 0, sizeof(buff) - BUFSEEDB);
- res = buff[0];
- for (i = 1; i < BUFSEED; i++)
- res ^= (res >> 3) + (res << 7) + buff[i];
- return res;
-}
-
-#endif
-
-
-LUALIB_API unsigned int luaL_makeseed (lua_State *L) {
- UNUSED(L);
- return luai_makeseed();
-}
-
-
-/*
-** Use the name with parentheses so that headers can redefine it
-** as a macro.
-*/
-LUALIB_API lua_State *(luaL_newstate) (void) {
- lua_State *L = lua_newstate(luaL_alloc, NULL, luaL_makeseed(NULL));
- if (l_likely(L)) {
- lua_atpanic(L, &panic);
- lua_setwarnf(L, warnfon, L);
- }
+LUALIB_API lua_State *luaL_newstate (void) {
+ lua_State *L = lua_newstate(l_alloc, NULL);
+ if (L) lua_atpanic(L, &panic);
return L;
}
LUALIB_API void luaL_checkversion_ (lua_State *L, lua_Number ver, size_t sz) {
- lua_Number v = lua_version(L);
+ const lua_Number *v = lua_version(L);
if (sz != LUAL_NUMSIZES) /* check numeric types */
luaL_error(L, "core and library have incompatible numeric types");
- else if (v != ver)
+ if (v != lua_version(NULL))
+ luaL_error(L, "multiple Lua VMs detected");
+ else if (*v != ver)
luaL_error(L, "version mismatch: app. needs %f, Lua core provides %f",
- (LUAI_UACNUMBER)ver, (LUAI_UACNUMBER)v);
+ ver, *v);
}
diff --git a/lauxlib.h b/src/lauxlib.h
similarity index 80%
rename from lauxlib.h
rename to src/lauxlib.h
index 2d015362ff..0bac2467ec 100644
--- a/lauxlib.h
+++ b/src/lauxlib.h
@@ -1,5 +1,5 @@
/*
-** $Id: lauxlib.h $
+** $Id: lauxlib.h,v 1.128 2014/10/29 16:11:17 roberto Exp $
** Auxiliary functions for building Lua libraries
** See Copyright Notice in lua.h
*/
@@ -12,29 +12,14 @@
#include
#include
-#include "luaconf.h"
#include "lua.h"
-/* global table */
-#define LUA_GNAME "_G"
-
-typedef struct luaL_Buffer luaL_Buffer;
-
-
-/* extra error code for 'luaL_loadfilex' */
+/* extra error code for 'luaL_load' */
#define LUA_ERRFILE (LUA_ERRERR+1)
-/* key, in the registry, for table of loaded modules */
-#define LUA_LOADED_TABLE "_LOADED"
-
-
-/* key, in the registry, for table of preloaded loaders */
-#define LUA_PRELOAD_TABLE "_PRELOAD"
-
-
typedef struct luaL_Reg {
const char *name;
lua_CFunction func;
@@ -51,7 +36,6 @@ 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 const char *(luaL_tolstring) (lua_State *L, int idx, size_t *len);
LUALIB_API int (luaL_argerror) (lua_State *L, int arg, const char *extramsg);
-LUALIB_API int (luaL_typeerror) (lua_State *L, int arg, const char *tname);
LUALIB_API const char *(luaL_checklstring) (lua_State *L, int arg,
size_t *l);
LUALIB_API const char *(luaL_optlstring) (lua_State *L, int arg,
@@ -81,11 +65,7 @@ LUALIB_API int (luaL_checkoption) (lua_State *L, int arg, const char *def,
LUALIB_API int (luaL_fileresult) (lua_State *L, int stat, const char *fname);
LUALIB_API int (luaL_execresult) (lua_State *L, int stat);
-LUALIB_API void *(luaL_alloc) (void *ud, void *ptr, size_t osize,
- size_t nsize);
-
-
-/* predefined references */
+/* pre-defined references */
#define LUA_NOREF (-2)
#define LUA_REFNIL (-1)
@@ -103,14 +83,10 @@ LUALIB_API int (luaL_loadstring) (lua_State *L, const char *s);
LUALIB_API lua_State *(luaL_newstate) (void);
-LUALIB_API unsigned (luaL_makeseed) (lua_State *L);
-
LUALIB_API lua_Integer (luaL_len) (lua_State *L, int idx);
-LUALIB_API void (luaL_addgsub) (luaL_Buffer *b, const char *s,
- const char *p, const char *r);
-LUALIB_API const char *(luaL_gsub) (lua_State *L, const char *s,
- const char *p, const char *r);
+LUALIB_API const char *(luaL_gsub) (lua_State *L, const char *s, const char *p,
+ const char *r);
LUALIB_API void (luaL_setfuncs) (lua_State *L, const luaL_Reg *l, int nup);
@@ -136,11 +112,7 @@ LUALIB_API void (luaL_requiref) (lua_State *L, const char *modname,
(luaL_checkversion(L), luaL_newlibtable(L,l), luaL_setfuncs(L,l,0))
#define luaL_argcheck(L, cond,arg,extramsg) \
- ((void)(luai_likely(cond) || luaL_argerror(L, (arg), (extramsg))))
-
-#define luaL_argexpected(L,cond,arg,tname) \
- ((void)(luai_likely(cond) || luaL_typeerror(L, (arg), (tname))))
-
+ ((void)((cond) || luaL_argerror(L, (arg), (extramsg))))
#define luaL_checkstring(L,n) (luaL_checklstring(L, (n), NULL))
#define luaL_optstring(L,n,d) (luaL_optlstring(L, (n), (d), NULL))
@@ -159,43 +131,19 @@ LUALIB_API void (luaL_requiref) (lua_State *L, const char *modname,
#define luaL_loadbuffer(L,s,sz,n) luaL_loadbufferx(L,s,sz,n,NULL)
-/*
-** Perform arithmetic operations on lua_Integer values with wrap-around
-** semantics, as the Lua core does.
-*/
-#define luaL_intop(op,v1,v2) \
- ((lua_Integer)((lua_Unsigned)(v1) op (lua_Unsigned)(v2)))
-
-
-/* push the value used to represent failure/error */
-#if defined(LUA_FAILISFALSE)
-#define luaL_pushfail(L) lua_pushboolean(L, 0)
-#else
-#define luaL_pushfail(L) lua_pushnil(L)
-#endif
-
-
-
/*
** {======================================================
** Generic Buffer manipulation
** =======================================================
*/
-struct luaL_Buffer {
+typedef struct luaL_Buffer {
char *b; /* buffer address */
size_t size; /* buffer size */
size_t n; /* number of characters in buffer */
lua_State *L;
- union {
- LUAI_MAXALIGN; /* ensure maximum alignment for buffer */
- char b[LUAL_BUFFERSIZE]; /* initial buffer */
- } init;
-};
-
-
-#define luaL_bufflen(bf) ((bf)->n)
-#define luaL_buffaddr(bf) ((bf)->b)
+ char initb[LUAL_BUFFERSIZE]; /* initial buffer */
+} luaL_Buffer;
#define luaL_addchar(B,c) \
@@ -204,8 +152,6 @@ struct luaL_Buffer {
#define luaL_addsize(B,s) ((B)->n += (s))
-#define luaL_buffsub(B,s) ((B)->n -= (s))
-
LUALIB_API void (luaL_buffinit) (lua_State *L, luaL_Buffer *B);
LUALIB_API char *(luaL_prepbuffsize) (luaL_Buffer *B, size_t sz);
LUALIB_API void (luaL_addlstring) (luaL_Buffer *B, const char *s, size_t l);
@@ -244,6 +190,45 @@ typedef struct luaL_Stream {
/* }====================================================== */
+
+/* compatibility with old module system */
+#if defined(LUA_COMPAT_MODULE)
+
+LUALIB_API void (luaL_pushmodule) (lua_State *L, const char *modname,
+ int sizehint);
+LUALIB_API void (luaL_openlib) (lua_State *L, const char *libname,
+ const luaL_Reg *l, int nup);
+
+#define luaL_register(L,n,l) (luaL_openlib(L,(n),(l),0))
+
+#endif
+
+
+/*
+** {==================================================================
+** "Abstraction Layer" for basic report of messages and errors
+** ===================================================================
+*/
+
+/* print a string */
+#if !defined(lua_writestring)
+#define lua_writestring(s,l) fwrite((s), sizeof(char), (l), stdout)
+#endif
+
+/* print a newline and flush the output */
+#if !defined(lua_writeline)
+#define lua_writeline() (lua_writestring("\n", 1), fflush(stdout))
+#endif
+
+/* print an error message */
+#if !defined(lua_writestringerror)
+#define lua_writestringerror(s,p) \
+ (fprintf(stderr, (s), (p)), fflush(stderr))
+#endif
+
+/* }================================================================== */
+
+
/*
** {============================================================
** Compatibility with deprecated conversions
diff --git a/lbaselib.c b/src/lbaselib.c
similarity index 65%
rename from lbaselib.c
rename to src/lbaselib.c
index 891bb90f48..a2403952f0 100644
--- a/lbaselib.c
+++ b/src/lbaselib.c
@@ -1,5 +1,5 @@
/*
-** $Id: lbaselib.c $
+** $Id: lbaselib.c,v 1.309 2014/12/10 12:26:42 roberto Exp $
** Basic library
** See Copyright Notice in lua.h
*/
@@ -19,18 +19,23 @@
#include "lauxlib.h"
#include "lualib.h"
-#include "llimits.h"
static int luaB_print (lua_State *L) {
int n = lua_gettop(L); /* number of arguments */
int i;
- for (i = 1; i <= n; i++) { /* for each argument */
+ lua_getglobal(L, "tostring");
+ for (i=1; i<=n; i++) {
+ const char *s;
size_t l;
- const char *s = luaL_tolstring(L, i, &l); /* convert it to string */
- if (i > 1) /* not the first element? */
- lua_writestring("\t", 1); /* add a tab before it */
- lua_writestring(s, l); /* print it */
+ lua_pushvalue(L, -1); /* function to be called */
+ lua_pushvalue(L, i); /* value to print */
+ lua_call(L, 1, 1);
+ s = lua_tolstring(L, -1, &l); /* get result */
+ if (s == NULL)
+ return luaL_error(L, "'tostring' must return a string to 'print'");
+ if (i>1) lua_writestring("\t", 1);
+ lua_writestring(s, l);
lua_pop(L, 1); /* pop result */
}
lua_writeline();
@@ -38,42 +43,23 @@ static int luaB_print (lua_State *L) {
}
-/*
-** Creates a warning with all given arguments.
-** Check first for errors; otherwise an error may interrupt
-** the composition of a warning, leaving it unfinished.
-*/
-static int luaB_warn (lua_State *L) {
- int n = lua_gettop(L); /* number of arguments */
- int i;
- luaL_checkstring(L, 1); /* at least one argument */
- for (i = 2; i <= n; i++)
- luaL_checkstring(L, i); /* make sure all arguments are strings */
- for (i = 1; i < n; i++) /* compose warning */
- lua_warning(L, lua_tostring(L, i), 1);
- lua_warning(L, lua_tostring(L, n), 0); /* close warning */
- return 0;
-}
-
-
#define SPACECHARS " \f\n\r\t\v"
-static const char *b_str2int (const char *s, unsigned base, lua_Integer *pn) {
+static const char *b_str2int (const char *s, int base, lua_Integer *pn) {
lua_Unsigned n = 0;
int neg = 0;
s += strspn(s, SPACECHARS); /* skip initial spaces */
- if (*s == '-') { s++; neg = 1; } /* handle sign */
+ if (*s == '-') { s++; neg = 1; } /* handle signal */
else if (*s == '+') s++;
- if (!isalnum(cast_uchar(*s))) /* no digit? */
+ if (!isalnum((unsigned char)*s)) /* no digit? */
return NULL;
do {
- unsigned digit = cast_uint(isdigit(cast_uchar(*s))
- ? *s - '0'
- : (toupper(cast_uchar(*s)) - 'A') + 10);
+ int digit = (isdigit((unsigned char)*s)) ? *s - '0'
+ : toupper((unsigned char)*s) - 'A' + 10;
if (digit >= base) return NULL; /* invalid numeral */
n = n * base + digit;
s++;
- } while (isalnum(cast_uchar(*s)));
+ } while (isalnum((unsigned char)*s));
s += strspn(s, SPACECHARS); /* skip trailing spaces */
*pn = (lua_Integer)((neg) ? (0u - n) : n);
return s;
@@ -82,6 +68,7 @@ static const char *b_str2int (const char *s, unsigned base, lua_Integer *pn) {
static int luaB_tonumber (lua_State *L) {
if (lua_isnoneornil(L, 2)) { /* standard conversion? */
+ luaL_checkany(L, 1);
if (lua_type(L, 1) == LUA_TNUMBER) { /* already a number? */
lua_settop(L, 1); /* yes; return it */
return 1;
@@ -92,7 +79,6 @@ static int luaB_tonumber (lua_State *L) {
if (s != NULL && lua_stringtonumber(L, s) == l + 1)
return 1; /* successful conversion to number */
/* else not a number */
- luaL_checkany(L, 1); /* (but there must be some parameter) */
}
}
else {
@@ -100,15 +86,15 @@ static int luaB_tonumber (lua_State *L) {
const char *s;
lua_Integer n = 0; /* to avoid warnings */
lua_Integer base = luaL_checkinteger(L, 2);
- luaL_checktype(L, 1, LUA_TSTRING); /* no numbers as strings */
- s = lua_tolstring(L, 1, &l);
+ luaL_checktype(L, 1, LUA_TSTRING); /* before 'luaL_checklstring'! */
+ s = luaL_checklstring(L, 1, &l);
luaL_argcheck(L, 2 <= base && base <= 36, 2, "base out of range");
- if (b_str2int(s, cast_uint(base), &n) == s + l) {
+ if (b_str2int(s, (int)base, &n) == s + l) {
lua_pushinteger(L, n);
return 1;
} /* else not a number */
} /* else not a number */
- luaL_pushfail(L); /* not a number */
+ lua_pushnil(L); /* not a number */
return 1;
}
@@ -116,8 +102,8 @@ static int luaB_tonumber (lua_State *L) {
static int luaB_error (lua_State *L) {
int level = (int)luaL_optinteger(L, 2, 1);
lua_settop(L, 1);
- if (lua_type(L, 1) == LUA_TSTRING && level > 0) {
- luaL_where(L, level); /* add extra information */
+ if (lua_isstring(L, 1) && level > 0) { /* add extra information? */
+ luaL_where(L, level);
lua_pushvalue(L, 1);
lua_concat(L, 2);
}
@@ -139,8 +125,9 @@ static int luaB_getmetatable (lua_State *L) {
static int luaB_setmetatable (lua_State *L) {
int t = lua_type(L, 2);
luaL_checktype(L, 1, LUA_TTABLE);
- luaL_argexpected(L, t == LUA_TNIL || t == LUA_TTABLE, 2, "nil or table");
- if (l_unlikely(luaL_getmetafield(L, 1, "__metatable") != LUA_TNIL))
+ luaL_argcheck(L, t == LUA_TNIL || t == LUA_TTABLE, 2,
+ "nil or table expected");
+ if (luaL_getmetafield(L, 1, "__metatable") != LUA_TNIL)
return luaL_error(L, "cannot change a protected metatable");
lua_settop(L, 2);
lua_setmetatable(L, 1);
@@ -158,9 +145,9 @@ static int luaB_rawequal (lua_State *L) {
static int luaB_rawlen (lua_State *L) {
int t = lua_type(L, 1);
- luaL_argexpected(L, t == LUA_TTABLE || t == LUA_TSTRING, 1,
- "table or string");
- lua_pushinteger(L, l_castU2S(lua_rawlen(L, 1)));
+ luaL_argcheck(L, t == LUA_TTABLE || t == LUA_TSTRING, 1,
+ "table or string expected");
+ lua_pushinteger(L, lua_rawlen(L, 1));
return 1;
}
@@ -183,88 +170,61 @@ static int luaB_rawset (lua_State *L) {
}
-static int pushmode (lua_State *L, int oldmode) {
- if (oldmode == -1)
- luaL_pushfail(L); /* invalid call to 'lua_gc' */
- else
- lua_pushstring(L, (oldmode == LUA_GCINC) ? "incremental"
- : "generational");
- return 1;
-}
-
-
-/*
-** check whether call to 'lua_gc' was valid (not inside a finalizer)
-*/
-#define checkvalres(res) { if (res == -1) break; }
-
static int luaB_collectgarbage (lua_State *L) {
static const char *const opts[] = {"stop", "restart", "collect",
- "count", "step", "isrunning", "generational", "incremental",
- "param", NULL};
- static const char optsnum[] = {LUA_GCSTOP, LUA_GCRESTART, LUA_GCCOLLECT,
- LUA_GCCOUNT, LUA_GCSTEP, LUA_GCISRUNNING, LUA_GCGEN, LUA_GCINC,
- LUA_GCPARAM};
+ "count", "step", "setpause", "setstepmul",
+ "isrunning", NULL};
+ static const int optsnum[] = {LUA_GCSTOP, LUA_GCRESTART, LUA_GCCOLLECT,
+ LUA_GCCOUNT, LUA_GCSTEP, LUA_GCSETPAUSE, LUA_GCSETSTEPMUL,
+ LUA_GCISRUNNING};
int o = optsnum[luaL_checkoption(L, 1, "collect", opts)];
+ int ex = (int)luaL_optinteger(L, 2, 0);
+ int res = lua_gc(L, o, ex);
switch (o) {
case LUA_GCCOUNT: {
- int k = lua_gc(L, o);
- int b = lua_gc(L, LUA_GCCOUNTB);
- checkvalres(k);
- lua_pushnumber(L, (lua_Number)k + ((lua_Number)b/1024));
+ int b = lua_gc(L, LUA_GCCOUNTB, 0);
+ lua_pushnumber(L, (lua_Number)res + ((lua_Number)b/1024));
return 1;
}
- case LUA_GCSTEP: {
- lua_Integer n = luaL_optinteger(L, 2, 0);
- int res = lua_gc(L, o, cast_sizet(n));
- checkvalres(res);
+ case LUA_GCSTEP: case LUA_GCISRUNNING: {
lua_pushboolean(L, res);
return 1;
}
- case LUA_GCISRUNNING: {
- int res = lua_gc(L, o);
- checkvalres(res);
- lua_pushboolean(L, res);
- return 1;
- }
- case LUA_GCGEN: {
- return pushmode(L, lua_gc(L, o));
- }
- case LUA_GCINC: {
- return pushmode(L, lua_gc(L, o));
- }
- case LUA_GCPARAM: {
- static const char *const params[] = {
- "minormul", "majorminor", "minormajor",
- "pause", "stepmul", "stepsize", NULL};
- static const char pnum[] = {
- LUA_GCPMINORMUL, LUA_GCPMAJORMINOR, LUA_GCPMINORMAJOR,
- LUA_GCPPAUSE, LUA_GCPSTEPMUL, LUA_GCPSTEPSIZE};
- int p = pnum[luaL_checkoption(L, 2, NULL, params)];
- lua_Integer value = luaL_optinteger(L, 3, -1);
- lua_pushinteger(L, lua_gc(L, o, p, (int)value));
- return 1;
- }
default: {
- int res = lua_gc(L, o);
- checkvalres(res);
lua_pushinteger(L, res);
return 1;
}
}
- luaL_pushfail(L); /* invalid call (inside a finalizer) */
- return 1;
}
+/*
+** This function has all type names as upvalues, to maximize performance.
+*/
static int luaB_type (lua_State *L) {
- int t = lua_type(L, 1);
- luaL_argcheck(L, t != LUA_TNONE, 1, "value expected");
- lua_pushstring(L, lua_typename(L, t));
+ luaL_checkany(L, 1);
+ lua_pushvalue(L, lua_upvalueindex(lua_type(L, 1) + 1));
return 1;
}
+static int pairsmeta (lua_State *L, const char *method, int iszero,
+ lua_CFunction iter) {
+ if (luaL_getmetafield(L, 1, method) == LUA_TNIL) { /* no metamethod? */
+ luaL_checktype(L, 1, LUA_TTABLE); /* argument must be a table */
+ lua_pushcfunction(L, iter); /* will return generator, */
+ lua_pushvalue(L, 1); /* state, */
+ if (iszero) lua_pushinteger(L, 0); /* and initial value */
+ else lua_pushnil(L);
+ }
+ else {
+ lua_pushvalue(L, 1); /* argument 'self' to metamethod */
+ lua_call(L, 1, 3); /* get 3 values from metamethod */
+ }
+ return 3;
+}
+
+
static int luaB_next (lua_State *L) {
luaL_checktype(L, 1, LUA_TTABLE);
lua_settop(L, 2); /* create a 2nd argument if there isn't one */
@@ -277,53 +237,54 @@ static int luaB_next (lua_State *L) {
}
-static int pairscont (lua_State *L, int status, lua_KContext k) {
- (void)L; (void)status; (void)k; /* unused */
- return 4; /* __pairs did all the work, just return its results */
+static int luaB_pairs (lua_State *L) {
+ return pairsmeta(L, "__pairs", 0, luaB_next);
}
-static int luaB_pairs (lua_State *L) {
- luaL_checkany(L, 1);
- if (luaL_getmetafield(L, 1, "__pairs") == LUA_TNIL) { /* no metamethod? */
- lua_pushcfunction(L, luaB_next); /* will return generator and */
- lua_pushvalue(L, 1); /* state */
- lua_pushnil(L); /* initial value */
- lua_pushnil(L); /* to-be-closed object */
- }
- else {
- lua_pushvalue(L, 1); /* argument 'self' to metamethod */
- lua_callk(L, 1, 4, 0, pairscont); /* get 4 values from metamethod */
- }
- return 4;
+
+/*
+** Traversal function for 'ipairs' for raw tables
+*/
+static int ipairsaux_raw (lua_State *L) {
+ lua_Integer i = luaL_checkinteger(L, 2) + 1;
+ luaL_checktype(L, 1, LUA_TTABLE);
+ lua_pushinteger(L, i);
+ return (lua_rawgeti(L, 1, i) == LUA_TNIL) ? 1 : 2;
}
/*
-** Traversal function for 'ipairs'
+** Traversal function for 'ipairs' for tables with metamethods
*/
static int ipairsaux (lua_State *L) {
- lua_Integer i = luaL_checkinteger(L, 2);
- i = luaL_intop(+, i, 1);
+ lua_Integer i = luaL_checkinteger(L, 2) + 1;
lua_pushinteger(L, i);
return (lua_geti(L, 1, i) == LUA_TNIL) ? 1 : 2;
}
/*
-** 'ipairs' function. Returns 'ipairsaux', given "table", 0.
-** (The given "table" may not be a table.)
+** This function will use either 'ipairsaux' or 'ipairsaux_raw' to
+** traverse a table, depending on whether the table has metamethods
+** that can affect the traversal.
*/
static int luaB_ipairs (lua_State *L) {
+ lua_CFunction iter = (luaL_getmetafield(L, 1, "__index") != LUA_TNIL)
+ ? ipairsaux : ipairsaux_raw;
+#if defined(LUA_COMPAT_IPAIRS)
+ return pairsmeta(L, "__ipairs", 1, iter);
+#else
luaL_checkany(L, 1);
- lua_pushcfunction(L, ipairsaux); /* iteration function */
+ lua_pushcfunction(L, iter); /* iteration function */
lua_pushvalue(L, 1); /* state */
lua_pushinteger(L, 0); /* initial value */
return 3;
+#endif
}
static int load_aux (lua_State *L, int status, int envidx) {
- if (l_likely(status == LUA_OK)) {
+ if (status == LUA_OK) {
if (envidx != 0) { /* 'env' parameter? */
lua_pushvalue(L, envidx); /* environment for loaded function */
if (!lua_setupvalue(L, -2, 1)) /* set it as 1st upvalue */
@@ -332,24 +293,16 @@ static int load_aux (lua_State *L, int status, int envidx) {
return 1;
}
else { /* error (message is on top of the stack) */
- luaL_pushfail(L);
+ lua_pushnil(L);
lua_insert(L, -2); /* put before error message */
- return 2; /* return fail plus error message */
+ return 2; /* return nil plus error message */
}
}
-static const char *getMode (lua_State *L, int idx) {
- const char *mode = luaL_optstring(L, idx, "bt");
- if (strchr(mode, 'B') != NULL) /* Lua code cannot use fixed buffers */
- luaL_argerror(L, idx, "invalid mode");
- return mode;
-}
-
-
static int luaB_loadfile (lua_State *L) {
const char *fname = luaL_optstring(L, 1, NULL);
- const char *mode = getMode(L, 2);
+ const char *mode = luaL_optstring(L, 2, NULL);
int env = (!lua_isnone(L, 3) ? 3 : 0); /* 'env' index or 0 if no 'env' */
int status = luaL_loadfilex(L, fname, mode);
return load_aux(L, status, env);
@@ -387,7 +340,7 @@ static const char *generic_reader (lua_State *L, void *ud, size_t *size) {
*size = 0;
return NULL;
}
- else if (l_unlikely(!lua_isstring(L, -1)))
+ else if (!lua_isstring(L, -1))
luaL_error(L, "reader function must return a string");
lua_replace(L, RESERVEDSLOT); /* save string in reserved slot */
return lua_tolstring(L, RESERVEDSLOT, size);
@@ -398,7 +351,7 @@ static int luaB_load (lua_State *L) {
int status;
size_t l;
const char *s = lua_tolstring(L, 1, &l);
- const char *mode = getMode(L, 3);
+ const char *mode = luaL_optstring(L, 3, "bt");
int env = (!lua_isnone(L, 4) ? 4 : 0); /* 'env' index or 0 if no 'env' */
if (s != NULL) { /* loading a string? */
const char *chunkname = luaL_optstring(L, 2, s);
@@ -425,7 +378,7 @@ static int dofilecont (lua_State *L, int d1, lua_KContext d2) {
static int luaB_dofile (lua_State *L) {
const char *fname = luaL_optstring(L, 1, NULL);
lua_settop(L, 1);
- if (l_unlikely(luaL_loadfile(L, fname) != LUA_OK))
+ if (luaL_loadfile(L, fname) != LUA_OK)
return lua_error(L);
lua_callk(L, 0, LUA_MULTRET, 0, dofilecont);
return dofilecont(L, 0, 0);
@@ -433,7 +386,7 @@ static int luaB_dofile (lua_State *L) {
static int luaB_assert (lua_State *L) {
- if (l_likely(lua_toboolean(L, 1))) /* condition is true? */
+ if (lua_toboolean(L, 1)) /* condition is true? */
return lua_gettop(L); /* return all arguments */
else { /* error */
luaL_checkany(L, 1); /* there must be a condition */
@@ -469,7 +422,7 @@ static int luaB_select (lua_State *L) {
** ignored).
*/
static int finishpcall (lua_State *L, int status, lua_KContext extra) {
- if (l_unlikely(status != LUA_OK && status != LUA_YIELD)) { /* error? */
+ if (status != LUA_OK && status != LUA_YIELD) { /* error? */
lua_pushboolean(L, 0); /* first result (false) */
lua_pushvalue(L, -2); /* error message */
return 2; /* return false, msg */
@@ -522,11 +475,13 @@ static const luaL_Reg base_funcs[] = {
{"ipairs", luaB_ipairs},
{"loadfile", luaB_loadfile},
{"load", luaB_load},
+#if defined(LUA_COMPAT_LOADSTRING)
+ {"loadstring", luaB_load},
+#endif
{"next", luaB_next},
{"pairs", luaB_pairs},
{"pcall", luaB_pcall},
{"print", luaB_print},
- {"warn", luaB_warn},
{"rawequal", luaB_rawequal},
{"rawlen", luaB_rawlen},
{"rawget", luaB_rawget},
@@ -535,25 +490,31 @@ static const luaL_Reg base_funcs[] = {
{"setmetatable", luaB_setmetatable},
{"tonumber", luaB_tonumber},
{"tostring", luaB_tostring},
- {"type", luaB_type},
{"xpcall", luaB_xpcall},
/* placeholders */
- {LUA_GNAME, NULL},
+ {"type", NULL},
+ {"_G", NULL},
{"_VERSION", NULL},
{NULL, NULL}
};
LUAMOD_API int luaopen_base (lua_State *L) {
+ int i;
/* open lib into global table */
lua_pushglobaltable(L);
luaL_setfuncs(L, base_funcs, 0);
/* set global _G */
lua_pushvalue(L, -1);
- lua_setfield(L, -2, LUA_GNAME);
+ lua_setfield(L, -2, "_G");
/* set global _VERSION */
lua_pushliteral(L, LUA_VERSION);
lua_setfield(L, -2, "_VERSION");
+ /* set function 'type' with proper upvalues */
+ for (i = 0; i < LUA_NUMTAGS; i++) /* push all type names as upvalues */
+ lua_pushstring(L, lua_typename(L, i));
+ lua_pushcclosure(L, luaB_type, LUA_NUMTAGS);
+ lua_setfield(L, -2, "type");
return 1;
}
diff --git a/src/lbitlib.c b/src/lbitlib.c
new file mode 100644
index 0000000000..15d5f0cdfc
--- /dev/null
+++ b/src/lbitlib.c
@@ -0,0 +1,230 @@
+/*
+** $Id: lbitlib.c,v 1.28 2014/11/02 19:19:04 roberto Exp $
+** Standard library for bitwise operations
+** See Copyright Notice in lua.h
+*/
+
+#define lbitlib_c
+#define LUA_LIB
+
+#include "lprefix.h"
+
+
+#include "lua.h"
+
+#include "lauxlib.h"
+#include "lualib.h"
+
+
+#if defined(LUA_COMPAT_BITLIB) /* { */
+
+
+/* number of bits to consider in a number */
+#if !defined(LUA_NBITS)
+#define LUA_NBITS 32
+#endif
+
+
+/*
+** a lua_Unsigned with its first LUA_NBITS bits equal to 1. (Shift must
+** be made in two parts to avoid problems when LUA_NBITS is equal to the
+** number of bits in a lua_Unsigned.)
+*/
+#define ALLONES (~(((~(lua_Unsigned)0) << (LUA_NBITS - 1)) << 1))
+
+
+/* macro to trim extra bits */
+#define trim(x) ((x) & ALLONES)
+
+
+/* builds a number with 'n' ones (1 <= n <= LUA_NBITS) */
+#define mask(n) (~((ALLONES << 1) << ((n) - 1)))
+
+
+
+static lua_Unsigned andaux (lua_State *L) {
+ int i, n = lua_gettop(L);
+ lua_Unsigned r = ~(lua_Unsigned)0;
+ for (i = 1; i <= n; i++)
+ r &= luaL_checkunsigned(L, i);
+ return trim(r);
+}
+
+
+static int b_and (lua_State *L) {
+ lua_Unsigned r = andaux(L);
+ lua_pushunsigned(L, r);
+ return 1;
+}
+
+
+static int b_test (lua_State *L) {
+ lua_Unsigned r = andaux(L);
+ lua_pushboolean(L, r != 0);
+ return 1;
+}
+
+
+static int b_or (lua_State *L) {
+ int i, n = lua_gettop(L);
+ lua_Unsigned r = 0;
+ for (i = 1; i <= n; i++)
+ r |= luaL_checkunsigned(L, i);
+ lua_pushunsigned(L, trim(r));
+ return 1;
+}
+
+
+static int b_xor (lua_State *L) {
+ int i, n = lua_gettop(L);
+ lua_Unsigned r = 0;
+ for (i = 1; i <= n; i++)
+ r ^= luaL_checkunsigned(L, i);
+ lua_pushunsigned(L, trim(r));
+ return 1;
+}
+
+
+static int b_not (lua_State *L) {
+ lua_Unsigned r = ~luaL_checkunsigned(L, 1);
+ lua_pushunsigned(L, trim(r));
+ return 1;
+}
+
+
+static int b_shift (lua_State *L, lua_Unsigned r, lua_Integer i) {
+ if (i < 0) { /* shift right? */
+ i = -i;
+ r = trim(r);
+ if (i >= LUA_NBITS) r = 0;
+ else r >>= i;
+ }
+ else { /* shift left */
+ if (i >= LUA_NBITS) r = 0;
+ else r <<= i;
+ r = trim(r);
+ }
+ lua_pushunsigned(L, r);
+ return 1;
+}
+
+
+static int b_lshift (lua_State *L) {
+ return b_shift(L, luaL_checkunsigned(L, 1), luaL_checkinteger(L, 2));
+}
+
+
+static int b_rshift (lua_State *L) {
+ return b_shift(L, luaL_checkunsigned(L, 1), -luaL_checkinteger(L, 2));
+}
+
+
+static int b_arshift (lua_State *L) {
+ lua_Unsigned r = luaL_checkunsigned(L, 1);
+ lua_Integer i = luaL_checkinteger(L, 2);
+ if (i < 0 || !(r & ((lua_Unsigned)1 << (LUA_NBITS - 1))))
+ return b_shift(L, r, -i);
+ else { /* arithmetic shift for 'negative' number */
+ if (i >= LUA_NBITS) r = ALLONES;
+ else
+ r = trim((r >> i) | ~(trim(~(lua_Unsigned)0) >> i)); /* add signal bit */
+ lua_pushunsigned(L, r);
+ return 1;
+ }
+}
+
+
+static int b_rot (lua_State *L, lua_Integer d) {
+ lua_Unsigned r = luaL_checkunsigned(L, 1);
+ int i = d & (LUA_NBITS - 1); /* i = d % NBITS */
+ r = trim(r);
+ if (i != 0) /* avoid undefined shift of LUA_NBITS when i == 0 */
+ r = (r << i) | (r >> (LUA_NBITS - i));
+ lua_pushunsigned(L, trim(r));
+ return 1;
+}
+
+
+static int b_lrot (lua_State *L) {
+ return b_rot(L, luaL_checkinteger(L, 2));
+}
+
+
+static int b_rrot (lua_State *L) {
+ return b_rot(L, -luaL_checkinteger(L, 2));
+}
+
+
+/*
+** get field and width arguments for field-manipulation functions,
+** checking whether they are valid.
+** ('luaL_error' called without 'return' to avoid later warnings about
+** 'width' being used uninitialized.)
+*/
+static int fieldargs (lua_State *L, int farg, int *width) {
+ lua_Integer f = luaL_checkinteger(L, farg);
+ lua_Integer w = luaL_optinteger(L, farg + 1, 1);
+ luaL_argcheck(L, 0 <= f, farg, "field cannot be negative");
+ luaL_argcheck(L, 0 < w, farg + 1, "width must be positive");
+ if (f + w > LUA_NBITS)
+ luaL_error(L, "trying to access non-existent bits");
+ *width = (int)w;
+ return (int)f;
+}
+
+
+static int b_extract (lua_State *L) {
+ int w;
+ lua_Unsigned r = trim(luaL_checkunsigned(L, 1));
+ int f = fieldargs(L, 2, &w);
+ r = (r >> f) & mask(w);
+ lua_pushunsigned(L, r);
+ return 1;
+}
+
+
+static int b_replace (lua_State *L) {
+ int w;
+ lua_Unsigned r = trim(luaL_checkunsigned(L, 1));
+ lua_Unsigned v = luaL_checkunsigned(L, 2);
+ int f = fieldargs(L, 3, &w);
+ int m = mask(w);
+ v &= m; /* erase bits outside given width */
+ r = (r & ~(m << f)) | (v << f);
+ lua_pushunsigned(L, r);
+ return 1;
+}
+
+
+static const luaL_Reg bitlib[] = {
+ {"arshift", b_arshift},
+ {"band", b_and},
+ {"bnot", b_not},
+ {"bor", b_or},
+ {"bxor", b_xor},
+ {"btest", b_test},
+ {"extract", b_extract},
+ {"lrotate", b_lrot},
+ {"lshift", b_lshift},
+ {"replace", b_replace},
+ {"rrotate", b_rrot},
+ {"rshift", b_rshift},
+ {NULL, NULL}
+};
+
+
+
+LUAMOD_API int luaopen_bit32 (lua_State *L) {
+ luaL_newlib(L, bitlib);
+ return 1;
+}
+
+
+#else /* }{ */
+
+
+LUAMOD_API int luaopen_bit32 (lua_State *L) {
+ return luaL_error(L, "library 'bit32' has been deprecated");
+}
+
+#endif /* } */
diff --git a/src/lcode.c b/src/lcode.c
new file mode 100644
index 0000000000..5e34624bf4
--- /dev/null
+++ b/src/lcode.c
@@ -0,0 +1,954 @@
+/*
+** $Id: lcode.c,v 2.99 2014/12/29 16:49:25 roberto Exp $
+** Code generator for Lua
+** See Copyright Notice in lua.h
+*/
+
+#define lcode_c
+#define LUA_CORE
+
+#include "lprefix.h"
+
+
+#include
+#include
+
+#include "lua.h"
+
+#include "lcode.h"
+#include "ldebug.h"
+#include "ldo.h"
+#include "lgc.h"
+#include "llex.h"
+#include "lmem.h"
+#include "lobject.h"
+#include "lopcodes.h"
+#include "lparser.h"
+#include "lstring.h"
+#include "ltable.h"
+#include "lvm.h"
+
+
+/* Maximum number of registers in a Lua function */
+#define MAXREGS 250
+
+
+#define hasjumps(e) ((e)->t != (e)->f)
+
+
+static int tonumeral(expdesc *e, TValue *v) {
+ if (e->t != NO_JUMP || e->f != NO_JUMP)
+ return 0; /* not a numeral */
+ switch (e->k) {
+ case VKINT:
+ if (v) setivalue(v, e->u.ival);
+ return 1;
+ case VKFLT:
+ if (v) setfltvalue(v, e->u.nval);
+ return 1;
+ default: return 0;
+ }
+}
+
+
+void luaK_nil (FuncState *fs, int from, int n) {
+ Instruction *previous;
+ int l = from + n - 1; /* last register to set nil */
+ if (fs->pc > fs->lasttarget) { /* no jumps to current position? */
+ previous = &fs->f->code[fs->pc-1];
+ if (GET_OPCODE(*previous) == OP_LOADNIL) {
+ int pfrom = GETARG_A(*previous);
+ int pl = pfrom + GETARG_B(*previous);
+ if ((pfrom <= from && from <= pl + 1) ||
+ (from <= pfrom && pfrom <= l + 1)) { /* can connect both? */
+ if (pfrom < from) from = pfrom; /* from = min(from, pfrom) */
+ if (pl > l) l = pl; /* l = max(l, pl) */
+ SETARG_A(*previous, from);
+ SETARG_B(*previous, l - from);
+ return;
+ }
+ } /* else go through */
+ }
+ luaK_codeABC(fs, OP_LOADNIL, from, n - 1, 0); /* else no optimization */
+}
+
+
+int luaK_jump (FuncState *fs) {
+ int jpc = fs->jpc; /* save list of jumps to here */
+ int j;
+ fs->jpc = NO_JUMP;
+ j = luaK_codeAsBx(fs, OP_JMP, 0, NO_JUMP);
+ luaK_concat(fs, &j, jpc); /* keep them on hold */
+ return j;
+}
+
+
+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);
+}
+
+
+static void fixjump (FuncState *fs, int pc, int dest) {
+ Instruction *jmp = &fs->f->code[pc];
+ int offset = dest-(pc+1);
+ lua_assert(dest != NO_JUMP);
+ if (abs(offset) > MAXARG_sBx)
+ luaX_syntaxerror(fs->ls, "control structure too long");
+ SETARG_sBx(*jmp, offset);
+}
+
+
+/*
+** returns current 'pc' and marks it as a jump target (to avoid wrong
+** optimizations with consecutive instructions not in the same basic block).
+*/
+int luaK_getlabel (FuncState *fs) {
+ fs->lasttarget = fs->pc;
+ return fs->pc;
+}
+
+
+static int getjump (FuncState *fs, int pc) {
+ int offset = GETARG_sBx(fs->f->code[pc]);
+ if (offset == NO_JUMP) /* point to itself represents end of list */
+ return NO_JUMP; /* end of list */
+ else
+ return (pc+1)+offset; /* turn offset into absolute position */
+}
+
+
+static Instruction *getjumpcontrol (FuncState *fs, int pc) {
+ Instruction *pi = &fs->f->code[pc];
+ if (pc >= 1 && testTMode(GET_OPCODE(*(pi-1))))
+ return pi-1;
+ else
+ return pi;
+}
+
+
+/*
+** 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) {
+ for (; list != NO_JUMP; list = getjump(fs, list)) {
+ Instruction i = *getjumpcontrol(fs, list);
+ if (GET_OPCODE(i) != OP_TESTSET) return 1;
+ }
+ return 0; /* not found */
+}
+
+
+static int patchtestreg (FuncState *fs, int node, int reg) {
+ Instruction *i = getjumpcontrol(fs, node);
+ if (GET_OPCODE(*i) != OP_TESTSET)
+ return 0; /* cannot patch other instructions */
+ if (reg != NO_REG && reg != GETARG_B(*i))
+ SETARG_A(*i, reg);
+ else /* no register to put value or register already has the value */
+ *i = CREATE_ABC(OP_TEST, GETARG_B(*i), 0, GETARG_C(*i));
+
+ return 1;
+}
+
+
+static void removevalues (FuncState *fs, int list) {
+ for (; list != NO_JUMP; list = getjump(fs, list))
+ patchtestreg(fs, list, NO_REG);
+}
+
+
+static void patchlistaux (FuncState *fs, int list, int vtarget, int reg,
+ int dtarget) {
+ while (list != NO_JUMP) {
+ int next = getjump(fs, list);
+ if (patchtestreg(fs, list, 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);
+ fs->jpc = NO_JUMP;
+}
+
+
+void luaK_patchlist (FuncState *fs, int list, int target) {
+ if (target == fs->pc)
+ luaK_patchtohere(fs, list);
+ else {
+ lua_assert(target < fs->pc);
+ patchlistaux(fs, list, target, NO_REG, target);
+ }
+}
+
+
+void luaK_patchclose (FuncState *fs, int list, int level) {
+ level++; /* argument is +1 to reserve 0 as non-op */
+ while (list != NO_JUMP) {
+ int next = getjump(fs, list);
+ lua_assert(GET_OPCODE(fs->f->code[list]) == OP_JMP &&
+ (GETARG_A(fs->f->code[list]) == 0 ||
+ GETARG_A(fs->f->code[list]) >= level));
+ SETARG_A(fs->f->code[list], level);
+ list = next;
+ }
+}
+
+
+void luaK_patchtohere (FuncState *fs, int list) {
+ luaK_getlabel(fs);
+ luaK_concat(fs, &fs->jpc, list);
+}
+
+
+void luaK_concat (FuncState *fs, int *l1, int l2) {
+ if (l2 == NO_JUMP) return;
+ else if (*l1 == NO_JUMP)
+ *l1 = l2;
+ else {
+ int list = *l1;
+ int next;
+ while ((next = getjump(fs, list)) != NO_JUMP) /* find last element */
+ list = next;
+ fixjump(fs, list, l2);
+ }
+}
+
+
+static int luaK_code (FuncState *fs, Instruction i) {
+ Proto *f = fs->f;
+ dischargejpc(fs); /* 'pc' will change */
+ /* put new instruction in code array */
+ luaM_growvector(fs->ls->L, f->code, fs->pc, f->sizecode, Instruction,
+ MAX_INT, "opcodes");
+ f->code[fs->pc] = i;
+ /* save corresponding line information */
+ luaM_growvector(fs->ls->L, f->lineinfo, fs->pc, f->sizelineinfo, int,
+ MAX_INT, "opcodes");
+ f->lineinfo[fs->pc] = fs->ls->lastline;
+ return fs->pc++;
+}
+
+
+int luaK_codeABC (FuncState *fs, OpCode o, int a, int b, int c) {
+ lua_assert(getOpMode(o) == iABC);
+ lua_assert(getBMode(o) != OpArgN || b == 0);
+ lua_assert(getCMode(o) != OpArgN || c == 0);
+ lua_assert(a <= MAXARG_A && b <= MAXARG_B && c <= MAXARG_C);
+ return luaK_code(fs, CREATE_ABC(o, a, b, c));
+}
+
+
+int luaK_codeABx (FuncState *fs, OpCode o, int a, unsigned int bc) {
+ lua_assert(getOpMode(o) == iABx || getOpMode(o) == iAsBx);
+ lua_assert(getCMode(o) == OpArgN);
+ lua_assert(a <= MAXARG_A && bc <= MAXARG_Bx);
+ return luaK_code(fs, CREATE_ABx(o, a, bc));
+}
+
+
+static int codeextraarg (FuncState *fs, int a) {
+ lua_assert(a <= MAXARG_Ax);
+ return luaK_code(fs, CREATE_Ax(OP_EXTRAARG, a));
+}
+
+
+int luaK_codek (FuncState *fs, int reg, int k) {
+ if (k <= MAXARG_Bx)
+ return luaK_codeABx(fs, OP_LOADK, reg, k);
+ else {
+ int p = luaK_codeABx(fs, OP_LOADKX, reg, 0);
+ codeextraarg(fs, k);
+ return p;
+ }
+}
+
+
+void luaK_checkstack (FuncState *fs, int n) {
+ int newstack = fs->freereg + n;
+ if (newstack > fs->f->maxstacksize) {
+ if (newstack >= MAXREGS)
+ luaX_syntaxerror(fs->ls, "function or expression too complex");
+ fs->f->maxstacksize = cast_byte(newstack);
+ }
+}
+
+
+void luaK_reserveregs (FuncState *fs, int n) {
+ luaK_checkstack(fs, n);
+ fs->freereg += n;
+}
+
+
+static void freereg (FuncState *fs, int reg) {
+ if (!ISK(reg) && reg >= fs->nactvar) {
+ fs->freereg--;
+ lua_assert(reg == fs->freereg);
+ }
+}
+
+
+static void freeexp (FuncState *fs, expdesc *e) {
+ if (e->k == VNONRELOC)
+ freereg(fs, e->u.info);
+}
+
+
+/*
+** Use scanner's table to cache position of constants in constant list
+** and try to reuse constants
+*/
+static int addk (FuncState *fs, TValue *key, TValue *v) {
+ lua_State *L = fs->ls->L;
+ Proto *f = fs->f;
+ TValue *idx = luaH_set(L, fs->ls->h, key); /* index scanner table */
+ int k, oldsize;
+ if (ttisinteger(idx)) { /* is there an index there? */
+ k = cast_int(ivalue(idx));
+ /* correct value? (warning: must distinguish floats from integers!) */
+ if (k < fs->nk && ttype(&f->k[k]) == ttype(v) &&
+ luaV_rawequalobj(&f->k[k], v))
+ return k; /* reuse index */
+ }
+ /* constant not found; create a new entry */
+ oldsize = f->sizek;
+ k = fs->nk;
+ /* numerical value does not need GC barrier;
+ table has no metatable, so it does not need to invalidate cache */
+ setivalue(idx, k);
+ luaM_growvector(L, f->k, k, f->sizek, TValue, MAXARG_Ax, "constants");
+ while (oldsize < f->sizek) setnilvalue(&f->k[oldsize++]);
+ setobj(L, &f->k[k], v);
+ fs->nk++;
+ luaC_barrier(L, f, v);
+ return k;
+}
+
+
+int luaK_stringK (FuncState *fs, TString *s) {
+ TValue o;
+ setsvalue(fs->ls->L, &o, s);
+ return addk(fs, &o, &o);
+}
+
+
+/*
+** Integers use userdata as keys to avoid collision with floats with same
+** value; conversion to 'void*' used only for hashing, no "precision"
+** problems
+*/
+int luaK_intK (FuncState *fs, lua_Integer n) {
+ TValue k, o;
+ setpvalue(&k, cast(void*, cast(size_t, n)));
+ setivalue(&o, n);
+ return addk(fs, &k, &o);
+}
+
+
+static int luaK_numberK (FuncState *fs, lua_Number r) {
+ TValue o;
+ setfltvalue(&o, r);
+ return addk(fs, &o, &o);
+}
+
+
+static int boolK (FuncState *fs, int b) {
+ TValue o;
+ setbvalue(&o, b);
+ return addk(fs, &o, &o);
+}
+
+
+static int nilK (FuncState *fs) {
+ TValue k, v;
+ setnilvalue(&v);
+ /* cannot use nil as key; instead use table itself to represent nil */
+ sethvalue(fs->ls->L, &k, fs->ls->h);
+ return addk(fs, &k, &v);
+}
+
+
+void luaK_setreturns (FuncState *fs, expdesc *e, int nresults) {
+ if (e->k == VCALL) { /* expression is an open function call? */
+ SETARG_C(getcode(fs, e), nresults+1);
+ }
+ else if (e->k == VVARARG) {
+ SETARG_B(getcode(fs, e), nresults+1);
+ SETARG_A(getcode(fs, e), fs->freereg);
+ luaK_reserveregs(fs, 1);
+ }
+}
+
+
+void luaK_setoneret (FuncState *fs, expdesc *e) {
+ if (e->k == VCALL) { /* expression is an open function call? */
+ e->k = VNONRELOC;
+ e->u.info = GETARG_A(getcode(fs, e));
+ }
+ else if (e->k == VVARARG) {
+ SETARG_B(getcode(fs, e), 2);
+ e->k = VRELOCABLE; /* can relocate its simple result */
+ }
+}
+
+
+void luaK_dischargevars (FuncState *fs, expdesc *e) {
+ switch (e->k) {
+ case VLOCAL: {
+ e->k = VNONRELOC;
+ break;
+ }
+ case VUPVAL: {
+ e->u.info = luaK_codeABC(fs, OP_GETUPVAL, 0, e->u.info, 0);
+ e->k = VRELOCABLE;
+ break;
+ }
+ case VINDEXED: {
+ OpCode op = OP_GETTABUP; /* assume 't' is in an upvalue */
+ freereg(fs, e->u.ind.idx);
+ if (e->u.ind.vt == VLOCAL) { /* 't' is in a register? */
+ freereg(fs, e->u.ind.t);
+ op = OP_GETTABLE;
+ }
+ e->u.info = luaK_codeABC(fs, op, 0, e->u.ind.t, e->u.ind.idx);
+ e->k = VRELOCABLE;
+ break;
+ }
+ case VVARARG:
+ case VCALL: {
+ luaK_setoneret(fs, e);
+ break;
+ }
+ default: break; /* there is one value available (somewhere) */
+ }
+}
+
+
+static int code_label (FuncState *fs, int A, int b, int jump) {
+ luaK_getlabel(fs); /* those instructions may be jump targets */
+ return luaK_codeABC(fs, OP_LOADBOOL, A, b, jump);
+}
+
+
+static void discharge2reg (FuncState *fs, expdesc *e, int reg) {
+ luaK_dischargevars(fs, e);
+ switch (e->k) {
+ case VNIL: {
+ luaK_nil(fs, reg, 1);
+ break;
+ }
+ case VFALSE: case VTRUE: {
+ luaK_codeABC(fs, OP_LOADBOOL, reg, e->k == VTRUE, 0);
+ break;
+ }
+ case VK: {
+ luaK_codek(fs, reg, e->u.info);
+ break;
+ }
+ case VKFLT: {
+ luaK_codek(fs, reg, luaK_numberK(fs, e->u.nval));
+ break;
+ }
+ case VKINT: {
+ luaK_codek(fs, reg, luaK_intK(fs, e->u.ival));
+ break;
+ }
+ case VRELOCABLE: {
+ Instruction *pc = &getcode(fs, e);
+ SETARG_A(*pc, reg);
+ break;
+ }
+ case VNONRELOC: {
+ if (reg != e->u.info)
+ luaK_codeABC(fs, OP_MOVE, reg, e->u.info, 0);
+ break;
+ }
+ default: {
+ lua_assert(e->k == VVOID || e->k == VJMP);
+ return; /* nothing to do... */
+ }
+ }
+ e->u.info = reg;
+ e->k = VNONRELOC;
+}
+
+
+static void discharge2anyreg (FuncState *fs, expdesc *e) {
+ if (e->k != VNONRELOC) {
+ luaK_reserveregs(fs, 1);
+ discharge2reg(fs, e, fs->freereg-1);
+ }
+}
+
+
+static void exp2reg (FuncState *fs, expdesc *e, int reg) {
+ discharge2reg(fs, e, reg);
+ if (e->k == VJMP)
+ luaK_concat(fs, &e->t, e->u.info); /* put this jump in 't' list */
+ if (hasjumps(e)) {
+ 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) || need_value(fs, e->f)) {
+ int fj = (e->k == VJMP) ? NO_JUMP : luaK_jump(fs);
+ p_f = code_label(fs, reg, 0, 1);
+ p_t = code_label(fs, reg, 1, 0);
+ luaK_patchtohere(fs, fj);
+ }
+ final = luaK_getlabel(fs);
+ patchlistaux(fs, e->f, final, reg, p_f);
+ patchlistaux(fs, e->t, final, reg, p_t);
+ }
+ e->f = e->t = NO_JUMP;
+ e->u.info = reg;
+ e->k = VNONRELOC;
+}
+
+
+void luaK_exp2nextreg (FuncState *fs, expdesc *e) {
+ luaK_dischargevars(fs, e);
+ freeexp(fs, e);
+ luaK_reserveregs(fs, 1);
+ exp2reg(fs, e, fs->freereg - 1);
+}
+
+
+int luaK_exp2anyreg (FuncState *fs, expdesc *e) {
+ luaK_dischargevars(fs, e);
+ if (e->k == VNONRELOC) {
+ if (!hasjumps(e)) return e->u.info; /* exp is already in a register */
+ if (e->u.info >= fs->nactvar) { /* reg. is not a local? */
+ exp2reg(fs, e, e->u.info); /* put value on it */
+ return e->u.info;
+ }
+ }
+ luaK_exp2nextreg(fs, e); /* default */
+ return e->u.info;
+}
+
+
+void luaK_exp2anyregup (FuncState *fs, expdesc *e) {
+ if (e->k != VUPVAL || hasjumps(e))
+ luaK_exp2anyreg(fs, e);
+}
+
+
+void luaK_exp2val (FuncState *fs, expdesc *e) {
+ if (hasjumps(e))
+ luaK_exp2anyreg(fs, e);
+ else
+ luaK_dischargevars(fs, e);
+}
+
+
+int luaK_exp2RK (FuncState *fs, expdesc *e) {
+ luaK_exp2val(fs, e);
+ switch (e->k) {
+ case VTRUE:
+ case VFALSE:
+ case VNIL: {
+ if (fs->nk <= MAXINDEXRK) { /* constant fits in RK operand? */
+ e->u.info = (e->k == VNIL) ? nilK(fs) : boolK(fs, (e->k == VTRUE));
+ e->k = VK;
+ return RKASK(e->u.info);
+ }
+ else break;
+ }
+ case VKINT: {
+ e->u.info = luaK_intK(fs, e->u.ival);
+ e->k = VK;
+ goto vk;
+ }
+ case VKFLT: {
+ e->u.info = luaK_numberK(fs, e->u.nval);
+ e->k = VK;
+ /* go through */
+ }
+ case VK: {
+ vk:
+ if (e->u.info <= MAXINDEXRK) /* constant fits in 'argC'? */
+ return RKASK(e->u.info);
+ else break;
+ }
+ default: break;
+ }
+ /* not a constant in the right range: put it in a register */
+ return luaK_exp2anyreg(fs, e);
+}
+
+
+void luaK_storevar (FuncState *fs, expdesc *var, expdesc *ex) {
+ switch (var->k) {
+ case VLOCAL: {
+ freeexp(fs, ex);
+ exp2reg(fs, ex, var->u.info);
+ return;
+ }
+ case VUPVAL: {
+ int e = luaK_exp2anyreg(fs, ex);
+ luaK_codeABC(fs, OP_SETUPVAL, e, var->u.info, 0);
+ break;
+ }
+ case VINDEXED: {
+ OpCode op = (var->u.ind.vt == VLOCAL) ? OP_SETTABLE : OP_SETTABUP;
+ int e = luaK_exp2RK(fs, ex);
+ luaK_codeABC(fs, op, var->u.ind.t, var->u.ind.idx, e);
+ break;
+ }
+ default: {
+ lua_assert(0); /* invalid var kind to store */
+ break;
+ }
+ }
+ freeexp(fs, ex);
+}
+
+
+void luaK_self (FuncState *fs, expdesc *e, expdesc *key) {
+ int ereg;
+ luaK_exp2anyreg(fs, e);
+ ereg = e->u.info; /* register where 'e' was placed */
+ freeexp(fs, e);
+ e->u.info = fs->freereg; /* base register for op_self */
+ e->k = VNONRELOC;
+ luaK_reserveregs(fs, 2); /* function and 'self' produced by op_self */
+ luaK_codeABC(fs, OP_SELF, e->u.info, ereg, luaK_exp2RK(fs, key));
+ freeexp(fs, key);
+}
+
+
+static void invertjump (FuncState *fs, expdesc *e) {
+ Instruction *pc = getjumpcontrol(fs, e->u.info);
+ lua_assert(testTMode(GET_OPCODE(*pc)) && GET_OPCODE(*pc) != OP_TESTSET &&
+ GET_OPCODE(*pc) != OP_TEST);
+ SETARG_A(*pc, !(GETARG_A(*pc)));
+}
+
+
+static int jumponcond (FuncState *fs, expdesc *e, int cond) {
+ if (e->k == VRELOCABLE) {
+ Instruction ie = getcode(fs, e);
+ if (GET_OPCODE(ie) == OP_NOT) {
+ fs->pc--; /* remove previous OP_NOT */
+ return condjump(fs, OP_TEST, GETARG_B(ie), 0, !cond);
+ }
+ /* else go through */
+ }
+ discharge2anyreg(fs, e);
+ freeexp(fs, e);
+ return condjump(fs, OP_TESTSET, NO_REG, e->u.info, cond);
+}
+
+
+void luaK_goiftrue (FuncState *fs, expdesc *e) {
+ int pc; /* pc of last jump */
+ luaK_dischargevars(fs, e);
+ switch (e->k) {
+ case VJMP: {
+ invertjump(fs, e);
+ pc = e->u.info;
+ break;
+ }
+ case VK: case VKFLT: case VKINT: case VTRUE: {
+ pc = NO_JUMP; /* always true; do nothing */
+ break;
+ }
+ default: {
+ pc = jumponcond(fs, e, 0);
+ break;
+ }
+ }
+ luaK_concat(fs, &e->f, pc); /* insert last jump in 'f' list */
+ luaK_patchtohere(fs, e->t);
+ e->t = NO_JUMP;
+}
+
+
+void luaK_goiffalse (FuncState *fs, expdesc *e) {
+ int pc; /* pc of last jump */
+ luaK_dischargevars(fs, e);
+ switch (e->k) {
+ case VJMP: {
+ pc = e->u.info;
+ break;
+ }
+ case VNIL: case VFALSE: {
+ pc = NO_JUMP; /* always false; do nothing */
+ break;
+ }
+ default: {
+ pc = jumponcond(fs, e, 1);
+ break;
+ }
+ }
+ luaK_concat(fs, &e->t, pc); /* insert last jump in 't' list */
+ luaK_patchtohere(fs, e->f);
+ e->f = NO_JUMP;
+}
+
+
+static void codenot (FuncState *fs, expdesc *e) {
+ luaK_dischargevars(fs, e);
+ switch (e->k) {
+ case VNIL: case VFALSE: {
+ e->k = VTRUE;
+ break;
+ }
+ case VK: case VKFLT: case VKINT: case VTRUE: {
+ e->k = VFALSE;
+ break;
+ }
+ case VJMP: {
+ invertjump(fs, e);
+ break;
+ }
+ case VRELOCABLE:
+ case VNONRELOC: {
+ discharge2anyreg(fs, e);
+ freeexp(fs, e);
+ e->u.info = luaK_codeABC(fs, OP_NOT, 0, e->u.info, 0);
+ e->k = VRELOCABLE;
+ break;
+ }
+ default: {
+ lua_assert(0); /* cannot happen */
+ break;
+ }
+ }
+ /* interchange true and false lists */
+ { int temp = e->f; e->f = e->t; e->t = temp; }
+ removevalues(fs, e->f);
+ removevalues(fs, e->t);
+}
+
+
+void luaK_indexed (FuncState *fs, expdesc *t, expdesc *k) {
+ lua_assert(!hasjumps(t));
+ t->u.ind.t = t->u.info;
+ t->u.ind.idx = luaK_exp2RK(fs, k);
+ t->u.ind.vt = (t->k == VUPVAL) ? VUPVAL
+ : check_exp(vkisinreg(t->k), VLOCAL);
+ t->k = VINDEXED;
+}
+
+
+/*
+** return false if folding can raise an error
+*/
+static int validop (int op, TValue *v1, TValue *v2) {
+ switch (op) {
+ case LUA_OPBAND: case LUA_OPBOR: case LUA_OPBXOR:
+ case LUA_OPSHL: case LUA_OPSHR: case LUA_OPBNOT: { /* conversion errors */
+ lua_Integer i;
+ return (tointeger(v1, &i) && tointeger(v2, &i));
+ }
+ case LUA_OPDIV: case LUA_OPIDIV: case LUA_OPMOD: /* division by 0 */
+ return (nvalue(v2) != 0);
+ default: return 1; /* everything else is valid */
+ }
+}
+
+
+/*
+** Try to "constant-fold" an operation; return 1 iff successful
+*/
+static int constfolding (FuncState *fs, int op, expdesc *e1, expdesc *e2) {
+ TValue v1, v2, res;
+ if (!tonumeral(e1, &v1) || !tonumeral(e2, &v2) || !validop(op, &v1, &v2))
+ return 0; /* non-numeric operands or not safe to fold */
+ luaO_arith(fs->ls->L, op, &v1, &v2, &res); /* does operation */
+ if (ttisinteger(&res)) {
+ e1->k = VKINT;
+ e1->u.ival = ivalue(&res);
+ }
+ else { /* folds neither NaN nor 0.0 (to avoid collapsing with -0.0) */
+ lua_Number n = fltvalue(&res);
+ if (luai_numisnan(n) || n == 0)
+ return 0;
+ e1->k = VKFLT;
+ e1->u.nval = n;
+ }
+ return 1;
+}
+
+
+/*
+** Code for binary and unary expressions that "produce values"
+** (arithmetic operations, bitwise operations, concat, length). First
+** try to do constant folding (only for numeric [arithmetic and
+** bitwise] operations, which is what 'lua_arith' accepts).
+** Expression to produce final result will be encoded in 'e1'.
+*/
+static void codeexpval (FuncState *fs, OpCode op,
+ expdesc *e1, expdesc *e2, int line) {
+ lua_assert(op >= OP_ADD);
+ if (op <= OP_BNOT && constfolding(fs, op - OP_ADD + LUA_OPADD, e1, e2))
+ return; /* result has been folded */
+ else {
+ int o1, o2;
+ /* move operands to registers (if needed) */
+ if (op == OP_UNM || op == OP_BNOT || op == OP_LEN) { /* unary op? */
+ o2 = 0; /* no second expression */
+ o1 = luaK_exp2anyreg(fs, e1); /* cannot operate on constants */
+ }
+ else { /* regular case (binary operators) */
+ o2 = luaK_exp2RK(fs, e2); /* both operands are "RK" */
+ o1 = luaK_exp2RK(fs, e1);
+ }
+ if (o1 > o2) { /* free registers in proper order */
+ freeexp(fs, e1);
+ freeexp(fs, e2);
+ }
+ else {
+ freeexp(fs, e2);
+ freeexp(fs, e1);
+ }
+ e1->u.info = luaK_codeABC(fs, op, 0, o1, o2); /* generate opcode */
+ e1->k = VRELOCABLE; /* all those operations are relocable */
+ luaK_fixline(fs, line);
+ }
+}
+
+
+static void codecomp (FuncState *fs, OpCode op, int cond, expdesc *e1,
+ expdesc *e2) {
+ int o1 = luaK_exp2RK(fs, e1);
+ int o2 = luaK_exp2RK(fs, e2);
+ freeexp(fs, e2);
+ freeexp(fs, e1);
+ if (cond == 0 && op != OP_EQ) {
+ int temp; /* exchange args to replace by '<' or '<=' */
+ temp = o1; o1 = o2; o2 = temp; /* o1 <==> o2 */
+ cond = 1;
+ }
+ e1->u.info = condjump(fs, op, cond, o1, o2);
+ e1->k = VJMP;
+}
+
+
+void luaK_prefix (FuncState *fs, UnOpr op, expdesc *e, int line) {
+ expdesc e2;
+ e2.t = e2.f = NO_JUMP; e2.k = VKINT; e2.u.ival = 0;
+ switch (op) {
+ case OPR_MINUS: case OPR_BNOT: case OPR_LEN: {
+ codeexpval(fs, cast(OpCode, (op - OPR_MINUS) + OP_UNM), e, &e2, line);
+ break;
+ }
+ case OPR_NOT: codenot(fs, e); break;
+ default: lua_assert(0);
+ }
+}
+
+
+void luaK_infix (FuncState *fs, BinOpr op, expdesc *v) {
+ switch (op) {
+ case OPR_AND: {
+ luaK_goiftrue(fs, v);
+ break;
+ }
+ case OPR_OR: {
+ luaK_goiffalse(fs, v);
+ break;
+ }
+ case OPR_CONCAT: {
+ luaK_exp2nextreg(fs, v); /* operand must be on the 'stack' */
+ break;
+ }
+ case OPR_ADD: case OPR_SUB:
+ case OPR_MUL: case OPR_DIV: case OPR_IDIV:
+ case OPR_MOD: case OPR_POW:
+ case OPR_BAND: case OPR_BOR: case OPR_BXOR:
+ case OPR_SHL: case OPR_SHR: {
+ if (!tonumeral(v, NULL)) luaK_exp2RK(fs, v);
+ break;
+ }
+ default: {
+ luaK_exp2RK(fs, v);
+ break;
+ }
+ }
+}
+
+
+void luaK_posfix (FuncState *fs, BinOpr op,
+ expdesc *e1, expdesc *e2, int line) {
+ switch (op) {
+ case OPR_AND: {
+ lua_assert(e1->t == NO_JUMP); /* list must be closed */
+ luaK_dischargevars(fs, e2);
+ luaK_concat(fs, &e2->f, e1->f);
+ *e1 = *e2;
+ break;
+ }
+ case OPR_OR: {
+ lua_assert(e1->f == NO_JUMP); /* list must be closed */
+ luaK_dischargevars(fs, e2);
+ luaK_concat(fs, &e2->t, e1->t);
+ *e1 = *e2;
+ break;
+ }
+ case OPR_CONCAT: {
+ luaK_exp2val(fs, e2);
+ if (e2->k == VRELOCABLE && GET_OPCODE(getcode(fs, e2)) == OP_CONCAT) {
+ lua_assert(e1->u.info == GETARG_B(getcode(fs, e2))-1);
+ freeexp(fs, e1);
+ SETARG_B(getcode(fs, e2), e1->u.info);
+ e1->k = VRELOCABLE; e1->u.info = e2->u.info;
+ }
+ else {
+ luaK_exp2nextreg(fs, e2); /* operand must be on the 'stack' */
+ codeexpval(fs, OP_CONCAT, e1, e2, line);
+ }
+ break;
+ }
+ case OPR_ADD: case OPR_SUB: case OPR_MUL: case OPR_DIV:
+ case OPR_IDIV: case OPR_MOD: case OPR_POW:
+ case OPR_BAND: case OPR_BOR: case OPR_BXOR:
+ case OPR_SHL: case OPR_SHR: {
+ codeexpval(fs, cast(OpCode, (op - OPR_ADD) + OP_ADD), e1, e2, line);
+ break;
+ }
+ case OPR_EQ: case OPR_LT: case OPR_LE: {
+ codecomp(fs, cast(OpCode, op - OPR_EQ + OP_EQ), 1, e1, e2);
+ break;
+ }
+ case OPR_NE: case OPR_GT: case OPR_GE: {
+ codecomp(fs, cast(OpCode, op - OPR_NE + OP_EQ), 0, e1, e2);
+ break;
+ }
+ default: lua_assert(0);
+ }
+}
+
+
+void luaK_fixline (FuncState *fs, int line) {
+ fs->f->lineinfo[fs->pc - 1] = line;
+}
+
+
+void luaK_setlist (FuncState *fs, int base, int nelems, int tostore) {
+ int c = (nelems - 1)/LFIELDS_PER_FLUSH + 1;
+ int b = (tostore == LUA_MULTRET) ? 0 : tostore;
+ lua_assert(tostore != 0);
+ if (c <= MAXARG_C)
+ luaK_codeABC(fs, OP_SETLIST, base, b, c);
+ else if (c <= MAXARG_Ax) {
+ luaK_codeABC(fs, OP_SETLIST, base, b, 0);
+ codeextraarg(fs, c);
+ }
+ else
+ luaX_syntaxerror(fs->ls, "constructor too long");
+ fs->freereg = base + 1; /* free registers with list values */
+}
+
diff --git a/lcode.h b/src/lcode.h
similarity index 63%
rename from lcode.h
rename to src/lcode.h
index 09e5c802b0..43ab86db77 100644
--- a/lcode.h
+++ b/src/lcode.h
@@ -1,5 +1,5 @@
/*
-** $Id: lcode.h $
+** $Id: lcode.h,v 1.63 2013/12/30 20:47:58 roberto Exp $
** Code generator for Lua
** See Copyright Notice in lua.h
*/
@@ -24,64 +24,49 @@
** grep "ORDER OPR" if you change these enums (ORDER OP)
*/
typedef enum BinOpr {
- /* arithmetic operators */
OPR_ADD, OPR_SUB, OPR_MUL, OPR_MOD, OPR_POW,
- OPR_DIV, OPR_IDIV,
- /* bitwise operators */
+ OPR_DIV,
+ OPR_IDIV,
OPR_BAND, OPR_BOR, OPR_BXOR,
OPR_SHL, OPR_SHR,
- /* string operator */
OPR_CONCAT,
- /* comparison operators */
OPR_EQ, OPR_LT, OPR_LE,
OPR_NE, OPR_GT, OPR_GE,
- /* logical operators */
OPR_AND, OPR_OR,
OPR_NOBINOPR
} BinOpr;
-/* true if operation is foldable (that is, it is arithmetic or bitwise) */
-#define foldbinop(op) ((op) <= OPR_SHR)
-
-
-#define luaK_codeABC(fs,o,a,b,c) luaK_codeABCk(fs,o,a,b,c,0)
-
-
typedef enum UnOpr { OPR_MINUS, OPR_BNOT, OPR_NOT, OPR_LEN, OPR_NOUNOPR } UnOpr;
-/* get (pointer to) instruction of given 'expdesc' */
-#define getinstruction(fs,e) ((fs)->f->code[(e)->u.info])
+#define getcode(fs,e) ((fs)->f->code[(e)->u.info])
+#define luaK_codeAsBx(fs,o,A,sBx) luaK_codeABx(fs,o,A,(sBx)+MAXARG_sBx)
#define luaK_setmultret(fs,e) luaK_setreturns(fs, e, LUA_MULTRET)
#define luaK_jumpto(fs,t) luaK_patchlist(fs, luaK_jump(fs), t)
-LUAI_FUNC int luaK_code (FuncState *fs, Instruction i);
-LUAI_FUNC int luaK_codeABx (FuncState *fs, OpCode o, int A, int Bx);
-LUAI_FUNC int luaK_codeABCk (FuncState *fs, OpCode o, int A, int B, int C,
- int k);
-LUAI_FUNC int luaK_codevABCk (FuncState *fs, OpCode o, int A, int B, int C,
- int k);
-LUAI_FUNC int luaK_exp2const (FuncState *fs, const expdesc *e, TValue *v);
+LUAI_FUNC int luaK_codeABx (FuncState *fs, OpCode o, int A, unsigned int Bx);
+LUAI_FUNC int luaK_codeABC (FuncState *fs, OpCode o, int A, int B, int C);
+LUAI_FUNC int luaK_codek (FuncState *fs, int reg, int k);
LUAI_FUNC void luaK_fixline (FuncState *fs, int line);
LUAI_FUNC void luaK_nil (FuncState *fs, int from, int n);
-LUAI_FUNC void luaK_codecheckglobal (FuncState *fs, expdesc *var, int k,
- int line);
LUAI_FUNC void luaK_reserveregs (FuncState *fs, int n);
LUAI_FUNC void luaK_checkstack (FuncState *fs, int n);
-LUAI_FUNC void luaK_int (FuncState *fs, int reg, lua_Integer n);
-LUAI_FUNC void luaK_vapar2local (FuncState *fs, expdesc *var);
+LUAI_FUNC int luaK_stringK (FuncState *fs, TString *s);
+LUAI_FUNC int luaK_intK (FuncState *fs, lua_Integer n);
LUAI_FUNC void luaK_dischargevars (FuncState *fs, expdesc *e);
LUAI_FUNC int luaK_exp2anyreg (FuncState *fs, expdesc *e);
LUAI_FUNC void luaK_exp2anyregup (FuncState *fs, expdesc *e);
LUAI_FUNC void luaK_exp2nextreg (FuncState *fs, expdesc *e);
LUAI_FUNC void luaK_exp2val (FuncState *fs, expdesc *e);
+LUAI_FUNC int luaK_exp2RK (FuncState *fs, expdesc *e);
LUAI_FUNC void luaK_self (FuncState *fs, expdesc *e, expdesc *key);
LUAI_FUNC void luaK_indexed (FuncState *fs, expdesc *t, expdesc *k);
LUAI_FUNC void luaK_goiftrue (FuncState *fs, expdesc *e);
+LUAI_FUNC void luaK_goiffalse (FuncState *fs, expdesc *e);
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);
@@ -89,17 +74,14 @@ 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_patchclose (FuncState *fs, int list, int level);
LUAI_FUNC void luaK_concat (FuncState *fs, int *l1, int l2);
LUAI_FUNC int luaK_getlabel (FuncState *fs);
LUAI_FUNC void luaK_prefix (FuncState *fs, UnOpr op, expdesc *v, int line);
LUAI_FUNC void luaK_infix (FuncState *fs, BinOpr op, expdesc *v);
LUAI_FUNC void luaK_posfix (FuncState *fs, BinOpr op, expdesc *v1,
expdesc *v2, int line);
-LUAI_FUNC void luaK_settablesize (FuncState *fs, int pc,
- int ra, int asize, int hsize);
LUAI_FUNC void luaK_setlist (FuncState *fs, int base, int nelems, int tostore);
-LUAI_FUNC void luaK_finish (FuncState *fs);
-LUAI_FUNC l_noret luaK_semerror (LexState *ls, const char *fmt, ...);
#endif
diff --git a/lcorolib.c b/src/lcorolib.c
similarity index 51%
rename from lcorolib.c
rename to src/lcorolib.c
index eb30bf4da5..0c0b7fa6b3 100644
--- a/lcorolib.c
+++ b/src/lcorolib.c
@@ -1,5 +1,5 @@
/*
-** $Id: lcorolib.c $
+** $Id: lcorolib.c,v 1.9 2014/11/02 19:19:04 roberto Exp $
** Coroutine Library
** See Copyright Notice in lua.h
*/
@@ -16,30 +16,30 @@
#include "lauxlib.h"
#include "lualib.h"
-#include "llimits.h"
static lua_State *getco (lua_State *L) {
lua_State *co = lua_tothread(L, 1);
- luaL_argexpected(L, co, 1, "thread");
+ luaL_argcheck(L, co, 1, "thread expected");
return co;
}
-/*
-** Resumes a coroutine. Returns the number of results for non-error
-** cases or -1 for errors.
-*/
static int auxresume (lua_State *L, lua_State *co, int narg) {
- int status, nres;
- if (l_unlikely(!lua_checkstack(co, narg))) {
+ int status;
+ if (!lua_checkstack(co, narg)) {
lua_pushliteral(L, "too many arguments to resume");
return -1; /* error flag */
}
+ if (lua_status(co) == LUA_OK && lua_gettop(co) == 0) {
+ lua_pushliteral(L, "cannot resume dead coroutine");
+ return -1; /* error flag */
+ }
lua_xmove(L, co, narg);
- status = lua_resume(co, L, narg, &nres);
- if (l_likely(status == LUA_OK || status == LUA_YIELD)) {
- if (l_unlikely(!lua_checkstack(L, nres + 1))) {
+ status = lua_resume(co, L, narg);
+ if (status == LUA_OK || status == LUA_YIELD) {
+ int nres = lua_gettop(co);
+ if (!lua_checkstack(L, nres + 1)) {
lua_pop(co, nres); /* remove results anyway */
lua_pushliteral(L, "too many results to resume");
return -1; /* error flag */
@@ -58,7 +58,7 @@ static int luaB_coresume (lua_State *L) {
lua_State *co = getco(L);
int r;
r = auxresume(L, co, lua_gettop(L) - 1);
- if (l_unlikely(r < 0)) {
+ if (r < 0) {
lua_pushboolean(L, 0);
lua_insert(L, -2);
return 2; /* return false + error message */
@@ -74,16 +74,9 @@ static int luaB_coresume (lua_State *L) {
static int luaB_auxwrap (lua_State *L) {
lua_State *co = lua_tothread(L, lua_upvalueindex(1));
int r = auxresume(L, co, lua_gettop(L));
- if (l_unlikely(r < 0)) { /* error? */
- int stat = lua_status(co);
- if (stat != LUA_OK && stat != LUA_YIELD) { /* error in the coroutine? */
- stat = lua_closethread(co, L); /* close its tbc variables */
- lua_assert(stat != LUA_OK);
- lua_xmove(co, L, 1); /* move error message to the caller */
- }
- if (stat != LUA_ERRMEM && /* not a memory error and ... */
- lua_type(L, -1) == LUA_TSTRING) { /* ... error object is a string? */
- luaL_where(L, 1); /* add extra info, if available */
+ if (r < 0) {
+ if (lua_isstring(L, -1)) { /* error object is a string? */
+ luaL_where(L, 1); /* add extra info */
lua_insert(L, -2);
lua_concat(L, 2);
}
@@ -115,53 +108,35 @@ static int luaB_yield (lua_State *L) {
}
-#define COS_RUN 0
-#define COS_DEAD 1
-#define COS_YIELD 2
-#define COS_NORM 3
-
-
-static const char *const statname[] =
- {"running", "dead", "suspended", "normal"};
-
-
-static int auxstatus (lua_State *L, lua_State *co) {
- if (L == co) return COS_RUN;
+static int luaB_costatus (lua_State *L) {
+ lua_State *co = getco(L);
+ if (L == co) lua_pushliteral(L, "running");
else {
switch (lua_status(co)) {
case LUA_YIELD:
- return COS_YIELD;
+ lua_pushliteral(L, "suspended");
+ break;
case LUA_OK: {
lua_Debug ar;
- if (lua_getstack(co, 0, &ar)) /* does it have frames? */
- return COS_NORM; /* it is running */
+ if (lua_getstack(co, 0, &ar) > 0) /* does it have frames? */
+ lua_pushliteral(L, "normal"); /* it is running */
else if (lua_gettop(co) == 0)
- return COS_DEAD;
+ lua_pushliteral(L, "dead");
else
- return COS_YIELD; /* initial state */
+ lua_pushliteral(L, "suspended"); /* initial state */
+ break;
}
default: /* some error occurred */
- return COS_DEAD;
+ lua_pushliteral(L, "dead");
+ break;
}
}
-}
-
-
-static int luaB_costatus (lua_State *L) {
- lua_State *co = getco(L);
- lua_pushstring(L, statname[auxstatus(L, co)]);
return 1;
}
-static lua_State *getoptco (lua_State *L) {
- return (lua_isnone(L, 1) ? L : getco(L));
-}
-
-
static int luaB_yieldable (lua_State *L) {
- lua_State *co = getoptco(L);
- lua_pushboolean(L, lua_isyieldable(co));
+ lua_pushboolean(L, lua_isyieldable(L));
return 1;
}
@@ -173,37 +148,6 @@ static int luaB_corunning (lua_State *L) {
}
-static int luaB_close (lua_State *L) {
- lua_State *co = getoptco(L);
- int status = auxstatus(L, co);
- switch (status) {
- case COS_DEAD: case COS_YIELD: {
- status = lua_closethread(co, L);
- if (status == LUA_OK) {
- lua_pushboolean(L, 1);
- return 1;
- }
- else {
- lua_pushboolean(L, 0);
- lua_xmove(co, L, 1); /* move error message */
- return 2;
- }
- }
- case COS_NORM:
- return luaL_error(L, "cannot close a %s coroutine", statname[status]);
- case COS_RUN:
- lua_geti(L, LUA_REGISTRYINDEX, LUA_RIDX_MAINTHREAD); /* get main */
- if (lua_tothread(L, -1) == co)
- return luaL_error(L, "cannot close main thread");
- lua_closethread(co, L); /* close itself */
- /* previous call does not return *//* FALLTHROUGH */
- default:
- lua_assert(0);
- return 0;
- }
-}
-
-
static const luaL_Reg co_funcs[] = {
{"create", luaB_cocreate},
{"resume", luaB_coresume},
@@ -212,7 +156,6 @@ static const luaL_Reg co_funcs[] = {
{"wrap", luaB_cowrap},
{"yield", luaB_yield},
{"isyieldable", luaB_yieldable},
- {"close", luaB_close},
{NULL, NULL}
};
diff --git a/lctype.c b/src/lctype.c
similarity index 52%
rename from lctype.c
rename to src/lctype.c
index b1a43e44b0..ae9367e691 100644
--- a/lctype.c
+++ b/src/lctype.c
@@ -1,5 +1,5 @@
/*
-** $Id: lctype.c $
+** $Id: lctype.c,v 1.12 2014/11/02 19:19:04 roberto Exp $
** 'ctype' functions for Lua
** See Copyright Notice in lua.h
*/
@@ -16,15 +16,6 @@
#include
-
-#if defined (LUA_UCID) /* accept UniCode IDentifiers? */
-/* consider all non-ASCII codepoints to be alphabetic */
-#define NONA 0x01
-#else
-#define NONA 0x00 /* default */
-#endif
-
-
LUAI_DDEF const lu_byte luai_ctype_[UCHAR_MAX + 2] = {
0x00, /* EOZ */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0. */
@@ -43,22 +34,22 @@ LUAI_DDEF const lu_byte luai_ctype_[UCHAR_MAX + 2] = {
0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05,
0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, /* 7. */
0x05, 0x05, 0x05, 0x04, 0x04, 0x04, 0x04, 0x00,
- NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, /* 8. */
- NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA,
- NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, /* 9. */
- NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA,
- NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, /* a. */
- NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA,
- NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, /* b. */
- NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA,
- 0x00, 0x00, NONA, NONA, NONA, NONA, NONA, NONA, /* c. */
- NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA,
- NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, /* d. */
- NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA,
- NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, /* e. */
- NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA,
- NONA, NONA, NONA, NONA, NONA, 0x00, 0x00, 0x00, /* f. */
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 8. */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 9. */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* a. */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* b. */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* c. */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* d. */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* e. */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* f. */
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
#endif /* } */
diff --git a/lctype.h b/src/lctype.h
similarity index 73%
rename from lctype.h
rename to src/lctype.h
index 864e190188..99c7d12237 100644
--- a/lctype.h
+++ b/src/lctype.h
@@ -1,5 +1,5 @@
/*
-** $Id: lctype.h $
+** $Id: lctype.h,v 1.12 2011/07/15 12:50:29 roberto Exp $
** 'ctype' functions for Lua
** See Copyright Notice in lua.h
*/
@@ -13,7 +13,7 @@
/*
** WARNING: the functions defined here do not necessarily correspond
** to the similar functions in the standard C ctype.h. They are
-** optimized for the specific needs of Lua.
+** optimized for the specific needs of Lua
*/
#if !defined(LUA_USE_CTYPE)
@@ -61,20 +61,14 @@
#define lisprint(c) testprop(c, MASK(PRINTBIT))
#define lisxdigit(c) testprop(c, MASK(XDIGITBIT))
-
/*
-** In ASCII, this 'ltolower' is correct for alphabetic characters and
-** for '.'. That is enough for Lua needs. ('check_exp' ensures that
-** the character either is an upper-case letter or is unchanged by
-** the transformation, which holds for lower-case letters and '.'.)
+** this 'ltolower' only works for alphabetic characters
*/
-#define ltolower(c) \
- check_exp(('A' <= (c) && (c) <= 'Z') || (c) == ((c) | ('A' ^ 'a')), \
- (c) | ('A' ^ 'a'))
+#define ltolower(c) ((c) | ('A' ^ 'a'))
-/* one entry for each character and for -1 (EOZ) */
-LUAI_DDEC(const lu_byte luai_ctype_[UCHAR_MAX + 2];)
+/* two more entries for 0 and -1 (EOZ) */
+LUAI_DDEC const lu_byte luai_ctype_[UCHAR_MAX + 2];
#else /* }{ */
diff --git a/ldblib.c b/src/ldblib.c
similarity index 79%
rename from ldblib.c
rename to src/ldblib.c
index c7b74812e8..24a11b53ee 100644
--- a/ldblib.c
+++ b/src/ldblib.c
@@ -1,5 +1,5 @@
/*
-** $Id: ldblib.c $
+** $Id: ldblib.c,v 1.148 2015/01/02 12:52:22 roberto Exp $
** Interface from Lua to its debug API
** See Copyright Notice in lua.h
*/
@@ -18,25 +18,13 @@
#include "lauxlib.h"
#include "lualib.h"
-#include "llimits.h"
/*
-** The hook table at registry[HOOKKEY] maps threads to their current
-** hook function.
+** The hook table at registry[&HOOKKEY] maps threads to their current
+** hook function. (We only need the unique address of 'HOOKKEY'.)
*/
-static const char *const HOOKKEY = "_HOOKKEY";
-
-
-/*
-** If L1 != L, L1 can be in any state, and therefore there are no
-** guarantees about its stack space; any push in L1 must be
-** checked.
-*/
-static void checkstack (lua_State *L, lua_State *L1, int n) {
- if (l_unlikely(L != L1 && !lua_checkstack(L1, n)))
- luaL_error(L, "stack overflow");
-}
+static const int HOOKKEY = 0;
static int db_getregistry (lua_State *L) {
@@ -56,7 +44,8 @@ static int db_getmetatable (lua_State *L) {
static int db_setmetatable (lua_State *L) {
int t = lua_type(L, 2);
- luaL_argexpected(L, t == LUA_TNIL || t == LUA_TTABLE, 2, "nil or table");
+ luaL_argcheck(L, t == LUA_TNIL || t == LUA_TTABLE, 2,
+ "nil or table expected");
lua_settop(L, 2);
lua_setmetatable(L, 1);
return 1; /* return 1st argument */
@@ -64,24 +53,19 @@ static int db_setmetatable (lua_State *L) {
static int db_getuservalue (lua_State *L) {
- int n = (int)luaL_optinteger(L, 2, 1);
if (lua_type(L, 1) != LUA_TUSERDATA)
- luaL_pushfail(L);
- else if (lua_getiuservalue(L, 1, n) != LUA_TNONE) {
- lua_pushboolean(L, 1);
- return 2;
- }
+ lua_pushnil(L);
+ else
+ lua_getuservalue(L, 1);
return 1;
}
static int db_setuservalue (lua_State *L) {
- int n = (int)luaL_optinteger(L, 3, 1);
luaL_checktype(L, 1, LUA_TUSERDATA);
luaL_checkany(L, 2);
lua_settop(L, 2);
- if (!lua_setiuservalue(L, 1, n))
- luaL_pushfail(L);
+ lua_setuservalue(L, 1);
return 1;
}
@@ -143,17 +127,12 @@ static void treatstackoption (lua_State *L, lua_State *L1, const char *fname) {
/*
** Calls 'lua_getinfo' and collects all results in a new table.
-** L1 needs stack space for an optional input (function) plus
-** two optional outputs (function and line table) from function
-** 'lua_getinfo'.
*/
static int db_getinfo (lua_State *L) {
lua_Debug ar;
int arg;
lua_State *L1 = getthread(L, &arg);
- const char *options = luaL_optstring(L, arg+2, "flnSrtu");
- checkstack(L, L1, 3);
- luaL_argcheck(L, options[0] != '>', arg + 2, "invalid option '>'");
+ const char *options = luaL_optstring(L, arg+2, "flnStu");
if (lua_isfunction(L, arg + 1)) { /* info about a function? */
options = lua_pushfstring(L, ">%s", options); /* add '>' to 'options' */
lua_pushvalue(L, arg + 1); /* move function to 'L1' stack */
@@ -161,7 +140,7 @@ static int db_getinfo (lua_State *L) {
}
else { /* stack level */
if (!lua_getstack(L1, (int)luaL_checkinteger(L, arg + 1), &ar)) {
- luaL_pushfail(L); /* level out of range */
+ lua_pushnil(L); /* level out of range */
return 1;
}
}
@@ -169,8 +148,7 @@ static int db_getinfo (lua_State *L) {
return luaL_argerror(L, arg+2, "invalid option");
lua_newtable(L); /* table to collect results */
if (strchr(options, 'S')) {
- lua_pushlstring(L, ar.source, ar.srclen);
- lua_setfield(L, -2, "source");
+ settabss(L, "source", ar.source);
settabss(L, "short_src", ar.short_src);
settabsi(L, "linedefined", ar.linedefined);
settabsi(L, "lastlinedefined", ar.lastlinedefined);
@@ -187,14 +165,8 @@ static int db_getinfo (lua_State *L) {
settabss(L, "name", ar.name);
settabss(L, "namewhat", ar.namewhat);
}
- if (strchr(options, 'r')) {
- settabsi(L, "ftransfer", ar.ftransfer);
- settabsi(L, "ntransfer", ar.ntransfer);
- }
- if (strchr(options, 't')) {
+ if (strchr(options, 't'))
settabsb(L, "istailcall", ar.istailcall);
- settabsi(L, "extraargs", ar.extraargs);
- }
if (strchr(options, 'L'))
treatstackoption(L, L1, "activelines");
if (strchr(options, 'f'))
@@ -206,6 +178,8 @@ static int db_getinfo (lua_State *L) {
static int db_getlocal (lua_State *L) {
int arg;
lua_State *L1 = getthread(L, &arg);
+ lua_Debug ar;
+ const char *name;
int nvar = (int)luaL_checkinteger(L, arg + 2); /* local-variable index */
if (lua_isfunction(L, arg + 1)) { /* function argument? */
lua_pushvalue(L, arg + 1); /* push function */
@@ -213,12 +187,9 @@ static int db_getlocal (lua_State *L) {
return 1; /* return only name (there is no value) */
}
else { /* stack-level argument */
- lua_Debug ar;
- const char *name;
int level = (int)luaL_checkinteger(L, arg + 1);
- if (l_unlikely(!lua_getstack(L1, level, &ar))) /* out of range? */
+ if (!lua_getstack(L1, level, &ar)) /* out of range? */
return luaL_argerror(L, arg+1, "level out of range");
- checkstack(L, L1, 1);
name = lua_getlocal(L1, &ar, nvar);
if (name) {
lua_xmove(L1, L, 1); /* move local value */
@@ -227,7 +198,7 @@ static int db_getlocal (lua_State *L) {
return 2;
}
else {
- luaL_pushfail(L); /* no name (nor value) */
+ lua_pushnil(L); /* no name (nor value) */
return 1;
}
}
@@ -241,11 +212,10 @@ static int db_setlocal (lua_State *L) {
lua_Debug ar;
int level = (int)luaL_checkinteger(L, arg + 1);
int nvar = (int)luaL_checkinteger(L, arg + 2);
- if (l_unlikely(!lua_getstack(L1, level, &ar))) /* out of range? */
+ if (!lua_getstack(L1, level, &ar)) /* out of range? */
return luaL_argerror(L, arg+1, "level out of range");
luaL_checkany(L, arg+3);
lua_settop(L, arg+3);
- checkstack(L, L1, 1);
lua_xmove(L, L1, 1);
name = lua_setlocal(L1, &ar, nvar);
if (name == NULL)
@@ -285,33 +255,25 @@ static int db_setupvalue (lua_State *L) {
** Check whether a given upvalue from a given closure exists and
** returns its index
*/
-static void *checkupval (lua_State *L, int argf, int argnup, int *pnup) {
- void *id;
+static int checkupval (lua_State *L, int argf, int argnup) {
int nup = (int)luaL_checkinteger(L, argnup); /* upvalue index */
luaL_checktype(L, argf, LUA_TFUNCTION); /* closure */
- id = lua_upvalueid(L, argf, nup);
- if (pnup) {
- luaL_argcheck(L, id != NULL, argnup, "invalid upvalue index");
- *pnup = nup;
- }
- return id;
+ luaL_argcheck(L, (lua_getupvalue(L, argf, nup) != NULL), argnup,
+ "invalid upvalue index");
+ return nup;
}
static int db_upvalueid (lua_State *L) {
- void *id = checkupval(L, 1, 2, NULL);
- if (id != NULL)
- lua_pushlightuserdata(L, id);
- else
- luaL_pushfail(L);
+ int n = checkupval(L, 1, 2);
+ lua_pushlightuserdata(L, lua_upvalueid(L, 1, n));
return 1;
}
static int db_upvaluejoin (lua_State *L) {
- int n1, n2;
- checkupval(L, 1, 2, &n1);
- checkupval(L, 3, 4, &n2);
+ int n1 = checkupval(L, 1, 2);
+ int n2 = checkupval(L, 3, 4);
luaL_argcheck(L, !lua_iscfunction(L, 1), 1, "Lua function expected");
luaL_argcheck(L, !lua_iscfunction(L, 3), 3, "Lua function expected");
lua_upvaluejoin(L, 1, n1, 3, n2);
@@ -326,7 +288,7 @@ static int db_upvaluejoin (lua_State *L) {
static void hookf (lua_State *L, lua_Debug *ar) {
static const char *const hooknames[] =
{"call", "return", "line", "count", "tail call"};
- lua_getfield(L, LUA_REGISTRYINDEX, HOOKKEY);
+ lua_rawgetp(L, LUA_REGISTRYINDEX, &HOOKKEY);
lua_pushthread(L);
if (lua_rawget(L, -2) == LUA_TFUNCTION) { /* is there a hook function? */
lua_pushstring(L, hooknames[(int)ar->event]); /* push event name */
@@ -379,14 +341,15 @@ static int db_sethook (lua_State *L) {
count = (int)luaL_optinteger(L, arg + 3, 0);
func = hookf; mask = makemask(smask, count);
}
- if (!luaL_getsubtable(L, LUA_REGISTRYINDEX, HOOKKEY)) {
- /* table just created; initialize it */
- lua_pushliteral(L, "k");
+ if (lua_rawgetp(L, LUA_REGISTRYINDEX, &HOOKKEY) == LUA_TNIL) {
+ lua_createtable(L, 0, 2); /* create a hook table */
+ lua_pushvalue(L, -1);
+ lua_rawsetp(L, LUA_REGISTRYINDEX, &HOOKKEY); /* set it in position */
+ lua_pushstring(L, "k");
lua_setfield(L, -2, "__mode"); /** hooktable.__mode = "k" */
lua_pushvalue(L, -1);
- lua_setmetatable(L, -2); /* metatable(hooktable) = hooktable */
+ lua_setmetatable(L, -2); /* setmetatable(hooktable) = hooktable */
}
- checkstack(L, L1, 1);
lua_pushthread(L1); lua_xmove(L1, L, 1); /* key (thread) */
lua_pushvalue(L, arg + 1); /* value (hook function) */
lua_rawset(L, -3); /* hooktable[L1] = new Lua hook */
@@ -401,15 +364,12 @@ static int db_gethook (lua_State *L) {
char buff[5];
int mask = lua_gethookmask(L1);
lua_Hook hook = lua_gethook(L1);
- if (hook == NULL) { /* no hook? */
- luaL_pushfail(L);
- return 1;
- }
+ if (hook == NULL) /* no hook? */
+ lua_pushnil(L);
else if (hook != hookf) /* external hook? */
lua_pushliteral(L, "external hook");
else { /* hook table must exist */
- lua_getfield(L, LUA_REGISTRYINDEX, HOOKKEY);
- checkstack(L, L1, 1);
+ lua_rawgetp(L, LUA_REGISTRYINDEX, &HOOKKEY);
lua_pushthread(L1); lua_xmove(L1, L, 1);
lua_rawget(L, -2); /* 1st result = hooktable[L1] */
lua_remove(L, -2); /* remove hook table */
@@ -424,12 +384,12 @@ static int db_debug (lua_State *L) {
for (;;) {
char buffer[250];
lua_writestringerror("%s", "lua_debug> ");
- if (fgets(buffer, sizeof(buffer), stdin) == NULL ||
+ if (fgets(buffer, sizeof(buffer), stdin) == 0 ||
strcmp(buffer, "cont\n") == 0)
return 0;
if (luaL_loadbuffer(L, buffer, strlen(buffer), "=(debug command)") ||
lua_pcall(L, 0, 0, 0))
- lua_writestringerror("%s\n", luaL_tolstring(L, -1, NULL));
+ lua_writestringerror("%s\n", lua_tostring(L, -1));
lua_settop(L, 0); /* remove eventual returns */
}
}
diff --git a/src/ldebug.c b/src/ldebug.c
new file mode 100644
index 0000000000..6986bf0f60
--- /dev/null
+++ b/src/ldebug.c
@@ -0,0 +1,643 @@
+/*
+** $Id: ldebug.c,v 2.110 2015/01/02 12:52:22 roberto Exp $
+** Debug Interface
+** See Copyright Notice in lua.h
+*/
+
+#define ldebug_c
+#define LUA_CORE
+
+#include "lprefix.h"
+
+
+#include
+#include
+#include
+
+#include "lua.h"
+
+#include "lapi.h"
+#include "lcode.h"
+#include "ldebug.h"
+#include "ldo.h"
+#include "lfunc.h"
+#include "lobject.h"
+#include "lopcodes.h"
+#include "lstate.h"
+#include "lstring.h"
+#include "ltable.h"
+#include "ltm.h"
+#include "lvm.h"
+
+
+
+#define noLuaClosure(f) ((f) == NULL || (f)->c.tt == LUA_TCCL)
+
+
+static const char *getfuncname (lua_State *L, CallInfo *ci, const char **name);
+
+
+static int currentpc (CallInfo *ci) {
+ lua_assert(isLua(ci));
+ return pcRel(ci->u.l.savedpc, ci_func(ci)->p);
+}
+
+
+static int currentline (CallInfo *ci) {
+ return getfuncline(ci_func(ci)->p, currentpc(ci));
+}
+
+
+/*
+** this function can be called asynchronous (e.g. during a signal)
+*/
+LUA_API void lua_sethook (lua_State *L, lua_Hook func, int mask, int count) {
+ if (func == NULL || mask == 0) { /* turn off hooks? */
+ mask = 0;
+ func = NULL;
+ }
+ if (isLua(L->ci))
+ L->oldpc = L->ci->u.l.savedpc;
+ L->hook = func;
+ L->basehookcount = count;
+ resethookcount(L);
+ L->hookmask = cast_byte(mask);
+}
+
+
+LUA_API lua_Hook lua_gethook (lua_State *L) {
+ return L->hook;
+}
+
+
+LUA_API int lua_gethookmask (lua_State *L) {
+ return L->hookmask;
+}
+
+
+LUA_API int lua_gethookcount (lua_State *L) {
+ return L->basehookcount;
+}
+
+
+LUA_API int lua_getstack (lua_State *L, int level, lua_Debug *ar) {
+ int status;
+ CallInfo *ci;
+ if (level < 0) return 0; /* invalid (negative) level */
+ lua_lock(L);
+ for (ci = L->ci; level > 0 && ci != &L->base_ci; ci = ci->previous)
+ level--;
+ if (level == 0 && ci != &L->base_ci) { /* level found? */
+ status = 1;
+ ar->i_ci = ci;
+ }
+ else status = 0; /* no such level */
+ lua_unlock(L);
+ return status;
+}
+
+
+static const char *upvalname (Proto *p, int uv) {
+ TString *s = check_exp(uv < p->sizeupvalues, p->upvalues[uv].name);
+ if (s == NULL) return "?";
+ else return getstr(s);
+}
+
+
+static const char *findvararg (CallInfo *ci, int n, StkId *pos) {
+ int nparams = clLvalue(ci->func)->p->numparams;
+ if (n >= ci->u.l.base - ci->func - nparams)
+ return NULL; /* no such vararg */
+ else {
+ *pos = ci->func + nparams + n;
+ return "(*vararg)"; /* generic name for any vararg */
+ }
+}
+
+
+static const char *findlocal (lua_State *L, CallInfo *ci, int n,
+ StkId *pos) {
+ const char *name = NULL;
+ StkId base;
+ if (isLua(ci)) {
+ if (n < 0) /* access to vararg values? */
+ return findvararg(ci, -n, pos);
+ else {
+ base = ci->u.l.base;
+ name = luaF_getlocalname(ci_func(ci)->p, n, currentpc(ci));
+ }
+ }
+ else
+ base = ci->func + 1;
+ if (name == NULL) { /* no 'standard' name? */
+ StkId limit = (ci == L->ci) ? L->top : ci->next->func;
+ if (limit - base >= n && n > 0) /* is 'n' inside 'ci' stack? */
+ name = "(*temporary)"; /* generic name for any valid slot */
+ else
+ return NULL; /* no name */
+ }
+ *pos = base + (n - 1);
+ return name;
+}
+
+
+LUA_API const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n) {
+ const char *name;
+ lua_lock(L);
+ if (ar == NULL) { /* information about non-active function? */
+ if (!isLfunction(L->top - 1)) /* not a Lua function? */
+ name = NULL;
+ else /* consider live variables at function start (parameters) */
+ name = luaF_getlocalname(clLvalue(L->top - 1)->p, n, 0);
+ }
+ else { /* active function; get information through 'ar' */
+ StkId pos = 0; /* to avoid warnings */
+ name = findlocal(L, ar->i_ci, n, &pos);
+ if (name) {
+ setobj2s(L, L->top, pos);
+ api_incr_top(L);
+ }
+ }
+ lua_unlock(L);
+ return name;
+}
+
+
+LUA_API const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n) {
+ StkId pos = 0; /* to avoid warnings */
+ const char *name = findlocal(L, ar->i_ci, n, &pos);
+ lua_lock(L);
+ if (name) {
+ setobjs2s(L, pos, L->top - 1);
+ L->top--; /* pop value */
+ }
+ lua_unlock(L);
+ return name;
+}
+
+
+static void funcinfo (lua_Debug *ar, Closure *cl) {
+ if (noLuaClosure(cl)) {
+ ar->source = "=[C]";
+ ar->linedefined = -1;
+ ar->lastlinedefined = -1;
+ ar->what = "C";
+ }
+ else {
+ Proto *p = cl->l.p;
+ ar->source = p->source ? getstr(p->source) : "=?";
+ ar->linedefined = p->linedefined;
+ ar->lastlinedefined = p->lastlinedefined;
+ ar->what = (ar->linedefined == 0) ? "main" : "Lua";
+ }
+ luaO_chunkid(ar->short_src, ar->source, LUA_IDSIZE);
+}
+
+
+static void collectvalidlines (lua_State *L, Closure *f) {
+ if (noLuaClosure(f)) {
+ setnilvalue(L->top);
+ api_incr_top(L);
+ }
+ else {
+ int i;
+ TValue v;
+ int *lineinfo = f->l.p->lineinfo;
+ Table *t = luaH_new(L); /* new table to store active lines */
+ sethvalue(L, L->top, t); /* push it on stack */
+ api_incr_top(L);
+ setbvalue(&v, 1); /* boolean 'true' to be the value of all indices */
+ for (i = 0; i < f->l.p->sizelineinfo; i++) /* for all lines with code */
+ luaH_setint(L, t, lineinfo[i], &v); /* table[line] = true */
+ }
+}
+
+
+static int auxgetinfo (lua_State *L, const char *what, lua_Debug *ar,
+ Closure *f, CallInfo *ci) {
+ int status = 1;
+ for (; *what; what++) {
+ switch (*what) {
+ case 'S': {
+ funcinfo(ar, f);
+ break;
+ }
+ case 'l': {
+ ar->currentline = (ci && isLua(ci)) ? currentline(ci) : -1;
+ break;
+ }
+ case 'u': {
+ ar->nups = (f == NULL) ? 0 : f->c.nupvalues;
+ if (noLuaClosure(f)) {
+ ar->isvararg = 1;
+ ar->nparams = 0;
+ }
+ else {
+ ar->isvararg = f->l.p->is_vararg;
+ ar->nparams = f->l.p->numparams;
+ }
+ break;
+ }
+ case 't': {
+ ar->istailcall = (ci) ? ci->callstatus & CIST_TAIL : 0;
+ break;
+ }
+ case 'n': {
+ /* calling function is a known Lua function? */
+ if (ci && !(ci->callstatus & CIST_TAIL) && isLua(ci->previous))
+ ar->namewhat = getfuncname(L, ci->previous, &ar->name);
+ else
+ ar->namewhat = NULL;
+ if (ar->namewhat == NULL) {
+ ar->namewhat = ""; /* not found */
+ ar->name = NULL;
+ }
+ break;
+ }
+ case 'L':
+ case 'f': /* handled by lua_getinfo */
+ break;
+ default: status = 0; /* invalid option */
+ }
+ }
+ return status;
+}
+
+
+LUA_API int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar) {
+ int status;
+ Closure *cl;
+ CallInfo *ci;
+ StkId func;
+ lua_lock(L);
+ if (*what == '>') {
+ ci = NULL;
+ func = L->top - 1;
+ api_check(ttisfunction(func), "function expected");
+ what++; /* skip the '>' */
+ L->top--; /* pop function */
+ }
+ else {
+ ci = ar->i_ci;
+ func = ci->func;
+ lua_assert(ttisfunction(ci->func));
+ }
+ cl = ttisclosure(func) ? clvalue(func) : NULL;
+ status = auxgetinfo(L, what, ar, cl, ci);
+ if (strchr(what, 'f')) {
+ setobjs2s(L, L->top, func);
+ api_incr_top(L);
+ }
+ if (strchr(what, 'L'))
+ collectvalidlines(L, cl);
+ lua_unlock(L);
+ return status;
+}
+
+
+/*
+** {======================================================
+** Symbolic Execution
+** =======================================================
+*/
+
+static const char *getobjname (Proto *p, int lastpc, int reg,
+ const char **name);
+
+
+/*
+** find a "name" for the RK value 'c'
+*/
+static void kname (Proto *p, int pc, int c, const char **name) {
+ if (ISK(c)) { /* is 'c' a constant? */
+ TValue *kvalue = &p->k[INDEXK(c)];
+ if (ttisstring(kvalue)) { /* literal constant? */
+ *name = svalue(kvalue); /* it is its own name */
+ return;
+ }
+ /* else no reasonable name found */
+ }
+ else { /* 'c' is a register */
+ const char *what = getobjname(p, pc, c, name); /* search for 'c' */
+ if (what && *what == 'c') { /* found a constant name? */
+ return; /* 'name' already filled */
+ }
+ /* else no reasonable name found */
+ }
+ *name = "?"; /* no reasonable name found */
+}
+
+
+static int filterpc (int pc, int jmptarget) {
+ if (pc < jmptarget) /* is code conditional (inside a jump)? */
+ return -1; /* cannot know who sets that register */
+ else return pc; /* current position sets that register */
+}
+
+
+/*
+** try to find last instruction before 'lastpc' that modified register 'reg'
+*/
+static int findsetreg (Proto *p, int lastpc, int reg) {
+ int pc;
+ int setreg = -1; /* keep last instruction that changed 'reg' */
+ int jmptarget = 0; /* any code before this address is conditional */
+ for (pc = 0; pc < lastpc; pc++) {
+ Instruction i = p->code[pc];
+ OpCode op = GET_OPCODE(i);
+ int a = GETARG_A(i);
+ switch (op) {
+ case OP_LOADNIL: {
+ int b = GETARG_B(i);
+ if (a <= reg && reg <= a + b) /* set registers from 'a' to 'a+b' */
+ setreg = filterpc(pc, jmptarget);
+ break;
+ }
+ case OP_TFORCALL: {
+ if (reg >= a + 2) /* affect all regs above its base */
+ setreg = filterpc(pc, jmptarget);
+ break;
+ }
+ case OP_CALL:
+ case OP_TAILCALL: {
+ if (reg >= a) /* affect all registers above base */
+ setreg = filterpc(pc, jmptarget);
+ break;
+ }
+ case OP_JMP: {
+ int b = GETARG_sBx(i);
+ int dest = pc + 1 + b;
+ /* jump is forward and do not skip 'lastpc'? */
+ if (pc < dest && dest <= lastpc) {
+ if (dest > jmptarget)
+ jmptarget = dest; /* update 'jmptarget' */
+ }
+ break;
+ }
+ default:
+ if (testAMode(op) && reg == a) /* any instruction that set A */
+ setreg = filterpc(pc, jmptarget);
+ break;
+ }
+ }
+ return setreg;
+}
+
+
+static const char *getobjname (Proto *p, int lastpc, int reg,
+ const char **name) {
+ int pc;
+ *name = luaF_getlocalname(p, reg + 1, lastpc);
+ if (*name) /* is a local? */
+ return "local";
+ /* else try symbolic execution */
+ pc = findsetreg(p, lastpc, reg);
+ if (pc != -1) { /* could find instruction? */
+ Instruction i = p->code[pc];
+ OpCode op = GET_OPCODE(i);
+ switch (op) {
+ case OP_MOVE: {
+ int b = GETARG_B(i); /* move from 'b' to 'a' */
+ if (b < GETARG_A(i))
+ return getobjname(p, pc, b, name); /* get name for 'b' */
+ break;
+ }
+ case OP_GETTABUP:
+ case OP_GETTABLE: {
+ int k = GETARG_C(i); /* key index */
+ int t = GETARG_B(i); /* table index */
+ const char *vn = (op == OP_GETTABLE) /* name of indexed variable */
+ ? luaF_getlocalname(p, t + 1, pc)
+ : upvalname(p, t);
+ kname(p, pc, k, name);
+ return (vn && strcmp(vn, LUA_ENV) == 0) ? "global" : "field";
+ }
+ case OP_GETUPVAL: {
+ *name = upvalname(p, GETARG_B(i));
+ return "upvalue";
+ }
+ case OP_LOADK:
+ case OP_LOADKX: {
+ int b = (op == OP_LOADK) ? GETARG_Bx(i)
+ : GETARG_Ax(p->code[pc + 1]);
+ if (ttisstring(&p->k[b])) {
+ *name = svalue(&p->k[b]);
+ return "constant";
+ }
+ break;
+ }
+ case OP_SELF: {
+ int k = GETARG_C(i); /* key index */
+ kname(p, pc, k, name);
+ return "method";
+ }
+ default: break; /* go through to return NULL */
+ }
+ }
+ return NULL; /* could not find reasonable name */
+}
+
+
+static const char *getfuncname (lua_State *L, CallInfo *ci, const char **name) {
+ TMS tm = (TMS)0; /* to avoid warnings */
+ Proto *p = ci_func(ci)->p; /* calling function */
+ int pc = currentpc(ci); /* calling instruction index */
+ Instruction i = p->code[pc]; /* calling instruction */
+ if (ci->callstatus & CIST_HOOKED) { /* was it called inside a hook? */
+ *name = "?";
+ return "hook";
+ }
+ switch (GET_OPCODE(i)) {
+ case OP_CALL:
+ case OP_TAILCALL: /* get function name */
+ return getobjname(p, pc, GETARG_A(i), name);
+ case OP_TFORCALL: { /* for iterator */
+ *name = "for iterator";
+ return "for iterator";
+ }
+ /* all other instructions can call only through metamethods */
+ case OP_SELF: case OP_GETTABUP: case OP_GETTABLE:
+ tm = TM_INDEX;
+ break;
+ case OP_SETTABUP: case OP_SETTABLE:
+ tm = TM_NEWINDEX;
+ break;
+ case OP_ADD: case OP_SUB: case OP_MUL: case OP_MOD:
+ case OP_POW: case OP_DIV: case OP_IDIV: case OP_BAND:
+ case OP_BOR: case OP_BXOR: case OP_SHL: case OP_SHR: {
+ int offset = cast_int(GET_OPCODE(i)) - cast_int(OP_ADD); /* ORDER OP */
+ tm = cast(TMS, offset + cast_int(TM_ADD)); /* ORDER TM */
+ break;
+ }
+ case OP_UNM: tm = TM_UNM; break;
+ case OP_BNOT: tm = TM_BNOT; break;
+ case OP_LEN: tm = TM_LEN; break;
+ case OP_CONCAT: tm = TM_CONCAT; break;
+ case OP_EQ: tm = TM_EQ; break;
+ case OP_LT: tm = TM_LT; break;
+ case OP_LE: tm = TM_LE; break;
+ default: lua_assert(0); /* other instructions cannot call a function */
+ }
+ *name = getstr(G(L)->tmname[tm]);
+ return "metamethod";
+}
+
+/* }====================================================== */
+
+
+
+/*
+** The subtraction of two potentially unrelated pointers is
+** not ISO C, but it should not crash a program; the subsequent
+** checks are ISO C and ensure a correct result.
+*/
+static int isinstack (CallInfo *ci, const TValue *o) {
+ ptrdiff_t i = o - ci->u.l.base;
+ return (0 <= i && i < (ci->top - ci->u.l.base) && ci->u.l.base + i == o);
+}
+
+
+/*
+** Checks whether value 'o' came from an upvalue. (That can only happen
+** with instructions OP_GETTABUP/OP_SETTABUP, which operate directly on
+** upvalues.)
+*/
+static const char *getupvalname (CallInfo *ci, const TValue *o,
+ const char **name) {
+ LClosure *c = ci_func(ci);
+ int i;
+ for (i = 0; i < c->nupvalues; i++) {
+ if (c->upvals[i]->v == o) {
+ *name = upvalname(c->p, i);
+ return "upvalue";
+ }
+ }
+ return NULL;
+}
+
+
+static const char *varinfo (lua_State *L, const TValue *o) {
+ const char *name = NULL; /* to avoid warnings */
+ CallInfo *ci = L->ci;
+ const char *kind = NULL;
+ if (isLua(ci)) {
+ kind = getupvalname(ci, o, &name); /* check whether 'o' is an upvalue */
+ if (!kind && isinstack(ci, o)) /* no? try a register */
+ kind = getobjname(ci_func(ci)->p, currentpc(ci),
+ cast_int(o - ci->u.l.base), &name);
+ }
+ return (kind) ? luaO_pushfstring(L, " (%s '%s')", kind, name) : "";
+}
+
+
+l_noret luaG_typeerror (lua_State *L, const TValue *o, const char *op) {
+ const char *t = objtypename(o);
+ luaG_runerror(L, "attempt to %s a %s value%s", op, t, varinfo(L, o));
+}
+
+
+l_noret luaG_concaterror (lua_State *L, const TValue *p1, const TValue *p2) {
+ if (ttisstring(p1) || cvt2str(p1)) p1 = p2;
+ luaG_typeerror(L, p1, "concatenate");
+}
+
+
+l_noret luaG_opinterror (lua_State *L, const TValue *p1,
+ const TValue *p2, const char *msg) {
+ lua_Number temp;
+ if (!tonumber(p1, &temp)) /* first operand is wrong? */
+ p2 = p1; /* now second is wrong */
+ luaG_typeerror(L, p2, msg);
+}
+
+
+/*
+** Error when both values are convertible to numbers, but not to integers
+*/
+l_noret luaG_tointerror (lua_State *L, const TValue *p1, const TValue *p2) {
+ lua_Integer temp;
+ if (!tointeger(p1, &temp))
+ p2 = p1;
+ luaG_runerror(L, "number%s has no integer representation", varinfo(L, p2));
+}
+
+
+l_noret luaG_ordererror (lua_State *L, const TValue *p1, const TValue *p2) {
+ const char *t1 = objtypename(p1);
+ const char *t2 = objtypename(p2);
+ if (t1 == t2)
+ luaG_runerror(L, "attempt to compare two %s values", t1);
+ else
+ luaG_runerror(L, "attempt to compare %s with %s", t1, t2);
+}
+
+
+static void addinfo (lua_State *L, const char *msg) {
+ CallInfo *ci = L->ci;
+ if (isLua(ci)) { /* is Lua code? */
+ char buff[LUA_IDSIZE]; /* add file:line information */
+ int line = currentline(ci);
+ TString *src = ci_func(ci)->p->source;
+ if (src)
+ luaO_chunkid(buff, getstr(src), LUA_IDSIZE);
+ else { /* no source available; use "?" instead */
+ buff[0] = '?'; buff[1] = '\0';
+ }
+ luaO_pushfstring(L, "%s:%d: %s", buff, line, msg);
+ }
+}
+
+
+l_noret luaG_errormsg (lua_State *L) {
+ if (L->errfunc != 0) { /* is there an error handling function? */
+ StkId errfunc = restorestack(L, L->errfunc);
+ setobjs2s(L, L->top, L->top - 1); /* move argument */
+ setobjs2s(L, L->top - 1, errfunc); /* push function */
+ L->top++; /* assume EXTRA_STACK */
+ luaD_call(L, L->top - 2, 1, 0); /* call it */
+ }
+ luaD_throw(L, LUA_ERRRUN);
+}
+
+
+l_noret luaG_runerror (lua_State *L, const char *fmt, ...) {
+ va_list argp;
+ va_start(argp, fmt);
+ addinfo(L, luaO_pushvfstring(L, fmt, argp));
+ va_end(argp);
+ luaG_errormsg(L);
+}
+
+
+void luaG_traceexec (lua_State *L) {
+ CallInfo *ci = L->ci;
+ lu_byte mask = L->hookmask;
+ int counthook = ((mask & LUA_MASKCOUNT) && L->hookcount == 0);
+ if (counthook)
+ resethookcount(L); /* reset count */
+ if (ci->callstatus & CIST_HOOKYIELD) { /* called hook last time? */
+ ci->callstatus &= ~CIST_HOOKYIELD; /* erase mark */
+ return; /* do not call hook again (VM yielded, so it did not move) */
+ }
+ if (counthook)
+ luaD_hook(L, LUA_HOOKCOUNT, -1); /* call count hook */
+ if (mask & LUA_MASKLINE) {
+ Proto *p = ci_func(ci)->p;
+ int npc = pcRel(ci->u.l.savedpc, p);
+ int newline = getfuncline(p, npc);
+ if (npc == 0 || /* call linehook when enter a new function, */
+ ci->u.l.savedpc <= L->oldpc || /* when jump back (loop), or when */
+ newline != getfuncline(p, pcRel(L->oldpc, p))) /* enter a new line */
+ luaD_hook(L, LUA_HOOKLINE, newline); /* call line hook */
+ }
+ L->oldpc = ci->u.l.savedpc;
+ if (L->status == LUA_YIELD) { /* did hook yield? */
+ if (counthook)
+ L->hookcount = 1; /* undo decrement to zero */
+ ci->u.l.savedpc--; /* undo increment (resume will increment it again) */
+ ci->callstatus |= CIST_HOOKYIELD; /* mark that it yielded */
+ ci->func = L->top - 1; /* protect stack below results */
+ luaD_throw(L, LUA_YIELD);
+ }
+}
+
diff --git a/src/ldebug.h b/src/ldebug.h
new file mode 100644
index 0000000000..0d8966ca9a
--- /dev/null
+++ b/src/ldebug.h
@@ -0,0 +1,40 @@
+/*
+** $Id: ldebug.h,v 2.12 2014/11/10 14:46:05 roberto Exp $
+** Auxiliary functions from Debug Interface module
+** See Copyright Notice in lua.h
+*/
+
+#ifndef ldebug_h
+#define ldebug_h
+
+
+#include "lstate.h"
+
+
+#define pcRel(pc, p) (cast(int, (pc) - (p)->code) - 1)
+
+#define getfuncline(f,pc) (((f)->lineinfo) ? (f)->lineinfo[pc] : -1)
+
+#define resethookcount(L) (L->hookcount = L->basehookcount)
+
+/* Active Lua function (given call info) */
+#define ci_func(ci) (clLvalue((ci)->func))
+
+
+LUAI_FUNC l_noret luaG_typeerror (lua_State *L, const TValue *o,
+ const char *opname);
+LUAI_FUNC l_noret luaG_concaterror (lua_State *L, const TValue *p1,
+ const TValue *p2);
+LUAI_FUNC l_noret luaG_opinterror (lua_State *L, const TValue *p1,
+ const TValue *p2,
+ const char *msg);
+LUAI_FUNC l_noret luaG_tointerror (lua_State *L, const TValue *p1,
+ const TValue *p2);
+LUAI_FUNC l_noret luaG_ordererror (lua_State *L, const TValue *p1,
+ const TValue *p2);
+LUAI_FUNC l_noret luaG_runerror (lua_State *L, const char *fmt, ...);
+LUAI_FUNC l_noret luaG_errormsg (lua_State *L);
+LUAI_FUNC void luaG_traceexec (lua_State *L);
+
+
+#endif
diff --git a/src/ldo.c b/src/ldo.c
new file mode 100644
index 0000000000..6159e51da2
--- /dev/null
+++ b/src/ldo.c
@@ -0,0 +1,717 @@
+/*
+** $Id: ldo.c,v 2.135 2014/11/11 17:13:39 roberto Exp $
+** Stack and Call structure of Lua
+** See Copyright Notice in lua.h
+*/
+
+#define ldo_c
+#define LUA_CORE
+
+#include "lprefix.h"
+
+
+#include
+#include
+#include
+
+#include "lua.h"
+
+#include "lapi.h"
+#include "ldebug.h"
+#include "ldo.h"
+#include "lfunc.h"
+#include "lgc.h"
+#include "lmem.h"
+#include "lobject.h"
+#include "lopcodes.h"
+#include "lparser.h"
+#include "lstate.h"
+#include "lstring.h"
+#include "ltable.h"
+#include "ltm.h"
+#include "lundump.h"
+#include "lvm.h"
+#include "lzio.h"
+
+
+
+#define errorstatus(s) ((s) > LUA_YIELD)
+
+
+/*
+** {======================================================
+** Error-recovery functions
+** =======================================================
+*/
+
+/*
+** LUAI_THROW/LUAI_TRY define how Lua does exception handling. By
+** default, Lua handles errors with exceptions when compiling as
+** C++ code, with _longjmp/_setjmp when asked to use them, and with
+** longjmp/setjmp otherwise.
+*/
+#if !defined(LUAI_THROW) /* { */
+
+#if defined(__cplusplus) && !defined(LUA_USE_LONGJMP) /* { */
+
+/* C++ exceptions */
+#define LUAI_THROW(L,c) throw(c)
+#define LUAI_TRY(L,c,a) \
+ try { a } catch(...) { if ((c)->status == 0) (c)->status = -1; }
+#define luai_jmpbuf int /* dummy variable */
+
+#elif defined(LUA_USE_POSIX) /* }{ */
+
+/* in POSIX, 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 }
+#define luai_jmpbuf jmp_buf
+
+#else /* }{ */
+
+/* ISO C handling with long jumps */
+#define LUAI_THROW(L,c) longjmp((c)->b, 1)
+#define LUAI_TRY(L,c,a) if (setjmp((c)->b) == 0) { a }
+#define luai_jmpbuf jmp_buf
+
+#endif /* } */
+
+#endif /* } */
+
+
+
+/* chain list of long jump buffers */
+struct lua_longjmp {
+ struct lua_longjmp *previous;
+ luai_jmpbuf b;
+ volatile int status; /* error code */
+};
+
+
+static void seterrorobj (lua_State *L, int errcode, StkId oldtop) {
+ switch (errcode) {
+ case LUA_ERRMEM: { /* memory error? */
+ setsvalue2s(L, oldtop, G(L)->memerrmsg); /* reuse preregistered msg. */
+ break;
+ }
+ case LUA_ERRERR: {
+ setsvalue2s(L, oldtop, luaS_newliteral(L, "error in error handling"));
+ break;
+ }
+ default: {
+ setobjs2s(L, oldtop, L->top - 1); /* error message on current top */
+ break;
+ }
+ }
+ L->top = oldtop + 1;
+}
+
+
+l_noret luaD_throw (lua_State *L, int errcode) {
+ if (L->errorJmp) { /* thread has an error handler? */
+ L->errorJmp->status = errcode; /* set status */
+ LUAI_THROW(L, L->errorJmp); /* jump to it */
+ }
+ else { /* thread has no error handler */
+ global_State *g = G(L);
+ L->status = cast_byte(errcode); /* mark it as dead */
+ if (g->mainthread->errorJmp) { /* main thread has a handler? */
+ setobjs2s(L, g->mainthread->top++, L->top - 1); /* copy error obj. */
+ luaD_throw(g->mainthread, errcode); /* re-throw in main thread */
+ }
+ else { /* no handler at all; abort */
+ if (g->panic) { /* panic function? */
+ seterrorobj(L, errcode, L->top); /* assume EXTRA_STACK */
+ if (L->ci->top < L->top)
+ L->ci->top = L->top; /* pushing msg. can break this invariant */
+ lua_unlock(L);
+ g->panic(L); /* call panic function (last chance to jump out) */
+ }
+ abort();
+ }
+ }
+}
+
+
+int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud) {
+ unsigned short oldnCcalls = L->nCcalls;
+ struct lua_longjmp lj;
+ lj.status = LUA_OK;
+ lj.previous = L->errorJmp; /* chain new error handler */
+ L->errorJmp = &lj;
+ LUAI_TRY(L, &lj,
+ (*f)(L, ud);
+ );
+ L->errorJmp = lj.previous; /* restore old error handler */
+ L->nCcalls = oldnCcalls;
+ return lj.status;
+}
+
+/* }====================================================== */
+
+
+static void correctstack (lua_State *L, TValue *oldstack) {
+ CallInfo *ci;
+ UpVal *up;
+ L->top = (L->top - oldstack) + L->stack;
+ for (up = L->openupval; up != NULL; up = up->u.open.next)
+ up->v = (up->v - oldstack) + L->stack;
+ for (ci = L->ci; ci != NULL; ci = ci->previous) {
+ ci->top = (ci->top - oldstack) + L->stack;
+ ci->func = (ci->func - oldstack) + L->stack;
+ if (isLua(ci))
+ ci->u.l.base = (ci->u.l.base - oldstack) + L->stack;
+ }
+}
+
+
+/* some space for error handling */
+#define ERRORSTACKSIZE (LUAI_MAXSTACK + 200)
+
+
+void luaD_reallocstack (lua_State *L, int newsize) {
+ TValue *oldstack = L->stack;
+ int lim = L->stacksize;
+ lua_assert(newsize <= LUAI_MAXSTACK || newsize == ERRORSTACKSIZE);
+ lua_assert(L->stack_last - L->stack == L->stacksize - EXTRA_STACK);
+ luaM_reallocvector(L, L->stack, L->stacksize, newsize, TValue);
+ for (; lim < newsize; lim++)
+ setnilvalue(L->stack + lim); /* erase new segment */
+ L->stacksize = newsize;
+ L->stack_last = L->stack + newsize - EXTRA_STACK;
+ correctstack(L, oldstack);
+}
+
+
+void luaD_growstack (lua_State *L, int n) {
+ int size = L->stacksize;
+ if (size > LUAI_MAXSTACK) /* error after extra size? */
+ luaD_throw(L, LUA_ERRERR);
+ else {
+ int needed = cast_int(L->top - L->stack) + n + EXTRA_STACK;
+ int newsize = 2 * size;
+ if (newsize > LUAI_MAXSTACK) newsize = LUAI_MAXSTACK;
+ if (newsize < needed) newsize = needed;
+ if (newsize > LUAI_MAXSTACK) { /* stack overflow? */
+ luaD_reallocstack(L, ERRORSTACKSIZE);
+ luaG_runerror(L, "stack overflow");
+ }
+ else
+ luaD_reallocstack(L, newsize);
+ }
+}
+
+
+static int stackinuse (lua_State *L) {
+ CallInfo *ci;
+ StkId lim = L->top;
+ for (ci = L->ci; ci != NULL; ci = ci->previous) {
+ lua_assert(ci->top <= L->stack_last);
+ if (lim < ci->top) lim = ci->top;
+ }
+ return cast_int(lim - L->stack) + 1; /* part of stack in use */
+}
+
+
+void luaD_shrinkstack (lua_State *L) {
+ int inuse = stackinuse(L);
+ int goodsize = inuse + (inuse / 8) + 2*EXTRA_STACK;
+ if (goodsize > LUAI_MAXSTACK) goodsize = LUAI_MAXSTACK;
+ if (L->stacksize > LUAI_MAXSTACK) /* was handling stack overflow? */
+ luaE_freeCI(L); /* free all CIs (list grew because of an error) */
+ else
+ luaE_shrinkCI(L); /* shrink list */
+ if (inuse > LUAI_MAXSTACK || /* still handling stack overflow? */
+ goodsize >= L->stacksize) /* would grow instead of shrink? */
+ condmovestack(L); /* don't change stack (change only for debugging) */
+ else
+ luaD_reallocstack(L, goodsize); /* shrink it */
+}
+
+
+void luaD_hook (lua_State *L, int event, int line) {
+ lua_Hook hook = L->hook;
+ if (hook && L->allowhook) {
+ CallInfo *ci = L->ci;
+ ptrdiff_t top = savestack(L, L->top);
+ ptrdiff_t ci_top = savestack(L, ci->top);
+ lua_Debug ar;
+ ar.event = event;
+ ar.currentline = line;
+ ar.i_ci = ci;
+ luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */
+ ci->top = L->top + LUA_MINSTACK;
+ lua_assert(ci->top <= L->stack_last);
+ L->allowhook = 0; /* cannot call hooks inside a hook */
+ ci->callstatus |= CIST_HOOKED;
+ lua_unlock(L);
+ (*hook)(L, &ar);
+ lua_lock(L);
+ lua_assert(!L->allowhook);
+ L->allowhook = 1;
+ ci->top = restorestack(L, ci_top);
+ L->top = restorestack(L, top);
+ ci->callstatus &= ~CIST_HOOKED;
+ }
+}
+
+
+static void callhook (lua_State *L, CallInfo *ci) {
+ int hook = LUA_HOOKCALL;
+ ci->u.l.savedpc++; /* hooks assume 'pc' is already incremented */
+ if (isLua(ci->previous) &&
+ GET_OPCODE(*(ci->previous->u.l.savedpc - 1)) == OP_TAILCALL) {
+ ci->callstatus |= CIST_TAIL;
+ hook = LUA_HOOKTAILCALL;
+ }
+ luaD_hook(L, hook, -1);
+ ci->u.l.savedpc--; /* correct 'pc' */
+}
+
+
+static StkId adjust_varargs (lua_State *L, Proto *p, int actual) {
+ int i;
+ int nfixargs = p->numparams;
+ StkId base, fixed;
+ lua_assert(actual >= nfixargs);
+ /* move fixed parameters to final position */
+ luaD_checkstack(L, p->maxstacksize); /* check again for new 'base' */
+ fixed = L->top - actual; /* first fixed argument */
+ base = L->top; /* final position of first argument */
+ for (i=0; itop++, fixed + i);
+ setnilvalue(fixed + i);
+ }
+ return base;
+}
+
+
+/*
+** Check whether __call metafield of 'func' is a function. If so, put
+** it in stack below original 'func' so that 'luaD_precall' can call
+** it. Raise an error if __call metafield is not a function.
+*/
+static void tryfuncTM (lua_State *L, StkId func) {
+ const TValue *tm = luaT_gettmbyobj(L, func, TM_CALL);
+ StkId p;
+ if (!ttisfunction(tm))
+ luaG_typeerror(L, func, "call");
+ /* Open a hole inside the stack at 'func' */
+ for (p = L->top; p > func; p--)
+ setobjs2s(L, p, p-1);
+ L->top++; /* slot ensured by caller */
+ setobj2s(L, func, tm); /* tag method is the new function to be called */
+}
+
+
+
+#define next_ci(L) (L->ci = (L->ci->next ? L->ci->next : luaE_extendCI(L)))
+
+
+/*
+** returns true if function has been executed (C function)
+*/
+int luaD_precall (lua_State *L, StkId func, int nresults) {
+ lua_CFunction f;
+ CallInfo *ci;
+ int n; /* number of arguments (Lua) or returns (C) */
+ ptrdiff_t funcr = savestack(L, func);
+ switch (ttype(func)) {
+ case LUA_TLCF: /* light C function */
+ f = fvalue(func);
+ goto Cfunc;
+ case LUA_TCCL: { /* C closure */
+ f = clCvalue(func)->f;
+ Cfunc:
+ luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */
+ ci = next_ci(L); /* now 'enter' new function */
+ ci->nresults = nresults;
+ ci->func = restorestack(L, funcr);
+ ci->top = L->top + LUA_MINSTACK;
+ lua_assert(ci->top <= L->stack_last);
+ ci->callstatus = 0;
+ luaC_checkGC(L); /* stack grow uses memory */
+ if (L->hookmask & LUA_MASKCALL)
+ luaD_hook(L, LUA_HOOKCALL, -1);
+ lua_unlock(L);
+ n = (*f)(L); /* do the actual call */
+ lua_lock(L);
+ api_checknelems(L, n);
+ luaD_poscall(L, L->top - n);
+ return 1;
+ }
+ case LUA_TLCL: { /* Lua function: prepare its call */
+ StkId base;
+ Proto *p = clLvalue(func)->p;
+ n = cast_int(L->top - func) - 1; /* number of real arguments */
+ luaD_checkstack(L, p->maxstacksize);
+ for (; n < p->numparams; n++)
+ setnilvalue(L->top++); /* complete missing arguments */
+ if (!p->is_vararg) {
+ func = restorestack(L, funcr);
+ base = func + 1;
+ }
+ else {
+ base = adjust_varargs(L, p, n);
+ func = restorestack(L, funcr); /* previous call can change stack */
+ }
+ ci = next_ci(L); /* now 'enter' new function */
+ ci->nresults = nresults;
+ ci->func = func;
+ ci->u.l.base = base;
+ ci->top = base + p->maxstacksize;
+ lua_assert(ci->top <= L->stack_last);
+ ci->u.l.savedpc = p->code; /* starting point */
+ ci->callstatus = CIST_LUA;
+ L->top = ci->top;
+ luaC_checkGC(L); /* stack grow uses memory */
+ if (L->hookmask & LUA_MASKCALL)
+ callhook(L, ci);
+ return 0;
+ }
+ default: { /* not a function */
+ luaD_checkstack(L, 1); /* ensure space for metamethod */
+ func = restorestack(L, funcr); /* previous call may change stack */
+ tryfuncTM(L, func); /* try to get '__call' metamethod */
+ return luaD_precall(L, func, nresults); /* now it must be a function */
+ }
+ }
+}
+
+
+int luaD_poscall (lua_State *L, StkId firstResult) {
+ StkId res;
+ int wanted, i;
+ CallInfo *ci = L->ci;
+ if (L->hookmask & (LUA_MASKRET | LUA_MASKLINE)) {
+ if (L->hookmask & LUA_MASKRET) {
+ ptrdiff_t fr = savestack(L, firstResult); /* hook may change stack */
+ luaD_hook(L, LUA_HOOKRET, -1);
+ firstResult = restorestack(L, fr);
+ }
+ L->oldpc = ci->previous->u.l.savedpc; /* 'oldpc' for caller function */
+ }
+ res = ci->func; /* res == final position of 1st result */
+ wanted = ci->nresults;
+ L->ci = ci = ci->previous; /* back to caller */
+ /* move results to correct place */
+ for (i = wanted; i != 0 && firstResult < L->top; i--)
+ setobjs2s(L, res++, firstResult++);
+ while (i-- > 0)
+ setnilvalue(res++);
+ L->top = res;
+ return (wanted - LUA_MULTRET); /* 0 iff wanted == LUA_MULTRET */
+}
+
+
+/*
+** Call a function (C or Lua). The function to be called is at *func.
+** The arguments are on the stack, right after the function.
+** When returns, all the results are on the stack, starting at the original
+** function position.
+*/
+void luaD_call (lua_State *L, StkId func, int nResults, int allowyield) {
+ if (++L->nCcalls >= LUAI_MAXCCALLS) {
+ if (L->nCcalls == LUAI_MAXCCALLS)
+ luaG_runerror(L, "C stack overflow");
+ else if (L->nCcalls >= (LUAI_MAXCCALLS + (LUAI_MAXCCALLS>>3)))
+ luaD_throw(L, LUA_ERRERR); /* error while handing stack error */
+ }
+ if (!allowyield) L->nny++;
+ if (!luaD_precall(L, func, nResults)) /* is a Lua function? */
+ luaV_execute(L); /* call it */
+ if (!allowyield) L->nny--;
+ L->nCcalls--;
+}
+
+
+/*
+** Completes the execution of an interrupted C function, calling its
+** continuation function.
+*/
+static void finishCcall (lua_State *L, int status) {
+ CallInfo *ci = L->ci;
+ int n;
+ /* must have a continuation and must be able to call it */
+ lua_assert(ci->u.c.k != NULL && L->nny == 0);
+ /* error status can only happen in a protected call */
+ lua_assert((ci->callstatus & CIST_YPCALL) || status == LUA_YIELD);
+ if (ci->callstatus & CIST_YPCALL) { /* was inside a pcall? */
+ ci->callstatus &= ~CIST_YPCALL; /* finish 'lua_pcall' */
+ L->errfunc = ci->u.c.old_errfunc;
+ }
+ /* finish 'lua_callk'/'lua_pcall'; CIST_YPCALL and 'errfunc' already
+ handled */
+ adjustresults(L, ci->nresults);
+ /* call continuation function */
+ lua_unlock(L);
+ n = (*ci->u.c.k)(L, status, ci->u.c.ctx);
+ lua_lock(L);
+ api_checknelems(L, n);
+ /* finish 'luaD_precall' */
+ luaD_poscall(L, L->top - n);
+}
+
+
+/*
+** Executes "full continuation" (everything in the stack) of a
+** previously interrupted coroutine until the stack is empty (or another
+** interruption long-jumps out of the loop). If the coroutine is
+** recovering from an error, 'ud' points to the error status, which must
+** be passed to the first continuation function (otherwise the default
+** status is LUA_YIELD).
+*/
+static void unroll (lua_State *L, void *ud) {
+ if (ud != NULL) /* error status? */
+ finishCcall(L, *(int *)ud); /* finish 'lua_pcallk' callee */
+ while (L->ci != &L->base_ci) { /* something in the stack */
+ if (!isLua(L->ci)) /* C function? */
+ finishCcall(L, LUA_YIELD); /* complete its execution */
+ else { /* Lua function */
+ luaV_finishOp(L); /* finish interrupted instruction */
+ luaV_execute(L); /* execute down to higher C 'boundary' */
+ }
+ }
+}
+
+
+/*
+** Try to find a suspended protected call (a "recover point") for the
+** given thread.
+*/
+static CallInfo *findpcall (lua_State *L) {
+ CallInfo *ci;
+ for (ci = L->ci; ci != NULL; ci = ci->previous) { /* search for a pcall */
+ if (ci->callstatus & CIST_YPCALL)
+ return ci;
+ }
+ return NULL; /* no pending pcall */
+}
+
+
+/*
+** Recovers from an error in a coroutine. Finds a recover point (if
+** there is one) and completes the execution of the interrupted
+** 'luaD_pcall'. If there is no recover point, returns zero.
+*/
+static int recover (lua_State *L, int status) {
+ StkId oldtop;
+ CallInfo *ci = findpcall(L);
+ if (ci == NULL) return 0; /* no recovery point */
+ /* "finish" luaD_pcall */
+ oldtop = restorestack(L, ci->extra);
+ luaF_close(L, oldtop);
+ seterrorobj(L, status, oldtop);
+ L->ci = ci;
+ L->allowhook = getoah(ci->callstatus); /* restore original 'allowhook' */
+ L->nny = 0; /* should be zero to be yieldable */
+ luaD_shrinkstack(L);
+ L->errfunc = ci->u.c.old_errfunc;
+ return 1; /* continue running the coroutine */
+}
+
+
+/*
+** signal an error in the call to 'resume', not in the execution of the
+** coroutine itself. (Such errors should not be handled by any coroutine
+** error handler and should not kill the coroutine.)
+*/
+static l_noret resume_error (lua_State *L, const char *msg, StkId firstArg) {
+ L->top = firstArg; /* remove args from the stack */
+ setsvalue2s(L, L->top, luaS_new(L, msg)); /* push error message */
+ api_incr_top(L);
+ luaD_throw(L, -1); /* jump back to 'lua_resume' */
+}
+
+
+/*
+** Do the work for 'lua_resume' in protected mode. Most of the work
+** depends on the status of the coroutine: initial state, suspended
+** inside a hook, or regularly suspended (optionally with a continuation
+** function), plus erroneous cases: non-suspended coroutine or dead
+** coroutine.
+*/
+static void resume (lua_State *L, void *ud) {
+ int nCcalls = L->nCcalls;
+ StkId firstArg = cast(StkId, ud);
+ CallInfo *ci = L->ci;
+ if (nCcalls >= LUAI_MAXCCALLS)
+ resume_error(L, "C stack overflow", firstArg);
+ if (L->status == LUA_OK) { /* may be starting a coroutine */
+ if (ci != &L->base_ci) /* not in base level? */
+ resume_error(L, "cannot resume non-suspended coroutine", firstArg);
+ /* coroutine is in base level; start running it */
+ if (!luaD_precall(L, firstArg - 1, LUA_MULTRET)) /* Lua function? */
+ luaV_execute(L); /* call it */
+ }
+ else if (L->status != LUA_YIELD)
+ resume_error(L, "cannot resume dead coroutine", firstArg);
+ else { /* resuming from previous yield */
+ L->status = LUA_OK; /* mark that it is running (again) */
+ ci->func = restorestack(L, ci->extra);
+ if (isLua(ci)) /* yielded inside a hook? */
+ luaV_execute(L); /* just continue running Lua code */
+ else { /* 'common' yield */
+ if (ci->u.c.k != NULL) { /* does it have a continuation function? */
+ int n;
+ lua_unlock(L);
+ n = (*ci->u.c.k)(L, LUA_YIELD, ci->u.c.ctx); /* call continuation */
+ lua_lock(L);
+ api_checknelems(L, n);
+ firstArg = L->top - n; /* yield results come from continuation */
+ }
+ luaD_poscall(L, firstArg); /* finish 'luaD_precall' */
+ }
+ unroll(L, NULL); /* run continuation */
+ }
+ lua_assert(nCcalls == L->nCcalls);
+}
+
+
+LUA_API int lua_resume (lua_State *L, lua_State *from, int nargs) {
+ int status;
+ int oldnny = L->nny; /* save "number of non-yieldable" calls */
+ lua_lock(L);
+ luai_userstateresume(L, nargs);
+ L->nCcalls = (from) ? from->nCcalls + 1 : 1;
+ L->nny = 0; /* allow yields */
+ api_checknelems(L, (L->status == LUA_OK) ? nargs + 1 : nargs);
+ status = luaD_rawrunprotected(L, resume, L->top - nargs);
+ if (status == -1) /* error calling 'lua_resume'? */
+ status = LUA_ERRRUN;
+ else { /* continue running after recoverable errors */
+ while (errorstatus(status) && recover(L, status)) {
+ /* unroll continuation */
+ status = luaD_rawrunprotected(L, unroll, &status);
+ }
+ if (errorstatus(status)) { /* unrecoverable error? */
+ L->status = cast_byte(status); /* mark thread as 'dead' */
+ seterrorobj(L, status, L->top); /* push error message */
+ L->ci->top = L->top;
+ }
+ else lua_assert(status == L->status); /* normal end or yield */
+ }
+ L->nny = oldnny; /* restore 'nny' */
+ L->nCcalls--;
+ lua_assert(L->nCcalls == ((from) ? from->nCcalls : 0));
+ lua_unlock(L);
+ return status;
+}
+
+
+LUA_API int lua_isyieldable (lua_State *L) {
+ return (L->nny == 0);
+}
+
+
+LUA_API int lua_yieldk (lua_State *L, int nresults, lua_KContext ctx,
+ lua_KFunction k) {
+ CallInfo *ci = L->ci;
+ luai_userstateyield(L, nresults);
+ lua_lock(L);
+ api_checknelems(L, nresults);
+ if (L->nny > 0) {
+ if (L != G(L)->mainthread)
+ luaG_runerror(L, "attempt to yield across a C-call boundary");
+ else
+ luaG_runerror(L, "attempt to yield from outside a coroutine");
+ }
+ L->status = LUA_YIELD;
+ ci->extra = savestack(L, ci->func); /* save current 'func' */
+ if (isLua(ci)) { /* inside a hook? */
+ api_check(k == NULL, "hooks cannot continue after yielding");
+ }
+ else {
+ if ((ci->u.c.k = k) != NULL) /* is there a continuation? */
+ ci->u.c.ctx = ctx; /* save context */
+ ci->func = L->top - nresults - 1; /* protect stack below results */
+ luaD_throw(L, LUA_YIELD);
+ }
+ lua_assert(ci->callstatus & CIST_HOOKED); /* must be inside a hook */
+ lua_unlock(L);
+ return 0; /* return to 'luaD_hook' */
+}
+
+
+int luaD_pcall (lua_State *L, Pfunc func, void *u,
+ ptrdiff_t old_top, ptrdiff_t ef) {
+ int status;
+ CallInfo *old_ci = L->ci;
+ lu_byte old_allowhooks = L->allowhook;
+ unsigned short old_nny = L->nny;
+ ptrdiff_t old_errfunc = L->errfunc;
+ L->errfunc = ef;
+ status = luaD_rawrunprotected(L, func, u);
+ if (status != LUA_OK) { /* an error occurred? */
+ StkId oldtop = restorestack(L, old_top);
+ luaF_close(L, oldtop); /* close possible pending closures */
+ seterrorobj(L, status, oldtop);
+ L->ci = old_ci;
+ L->allowhook = old_allowhooks;
+ L->nny = old_nny;
+ luaD_shrinkstack(L);
+ }
+ L->errfunc = old_errfunc;
+ return status;
+}
+
+
+
+/*
+** Execute a protected parser.
+*/
+struct SParser { /* data to 'f_parser' */
+ ZIO *z;
+ Mbuffer buff; /* dynamic structure used by the scanner */
+ Dyndata dyd; /* dynamic structures used by the parser */
+ const char *mode;
+ const char *name;
+};
+
+
+static void checkmode (lua_State *L, const char *mode, const char *x) {
+ if (mode && strchr(mode, x[0]) == NULL) {
+ luaO_pushfstring(L,
+ "attempt to load a %s chunk (mode is '%s')", x, mode);
+ luaD_throw(L, LUA_ERRSYNTAX);
+ }
+}
+
+
+static void f_parser (lua_State *L, void *ud) {
+ LClosure *cl;
+ struct SParser *p = cast(struct SParser *, ud);
+ int c = zgetc(p->z); /* read first character */
+ if (c == LUA_SIGNATURE[0]) {
+ checkmode(L, p->mode, "binary");
+ cl = luaU_undump(L, p->z, &p->buff, p->name);
+ }
+ else {
+ checkmode(L, p->mode, "text");
+ cl = luaY_parser(L, p->z, &p->buff, &p->dyd, p->name, c);
+ }
+ lua_assert(cl->nupvalues == cl->p->sizeupvalues);
+ luaF_initupvals(L, cl);
+}
+
+
+int luaD_protectedparser (lua_State *L, ZIO *z, const char *name,
+ const char *mode) {
+ struct SParser p;
+ int status;
+ L->nny++; /* cannot yield during parsing */
+ p.z = z; p.name = name; p.mode = mode;
+ p.dyd.actvar.arr = NULL; p.dyd.actvar.size = 0;
+ p.dyd.gt.arr = NULL; p.dyd.gt.size = 0;
+ p.dyd.label.arr = NULL; p.dyd.label.size = 0;
+ luaZ_initbuffer(L, &p.buff);
+ status = luaD_pcall(L, f_parser, &p, savestack(L, L->top), L->errfunc);
+ luaZ_freebuffer(L, &p.buff);
+ luaM_freearray(L, p.dyd.actvar.arr, p.dyd.actvar.size);
+ luaM_freearray(L, p.dyd.gt.arr, p.dyd.gt.size);
+ luaM_freearray(L, p.dyd.label.arr, p.dyd.label.size);
+ L->nny--;
+ return status;
+}
+
+
diff --git a/src/ldo.h b/src/ldo.h
new file mode 100644
index 0000000000..05745c8ad8
--- /dev/null
+++ b/src/ldo.h
@@ -0,0 +1,46 @@
+/*
+** $Id: ldo.h,v 2.21 2014/10/25 11:50:46 roberto Exp $
+** Stack and Call structure of Lua
+** See Copyright Notice in lua.h
+*/
+
+#ifndef ldo_h
+#define ldo_h
+
+
+#include "lobject.h"
+#include "lstate.h"
+#include "lzio.h"
+
+
+#define luaD_checkstack(L,n) if (L->stack_last - L->top <= (n)) \
+ luaD_growstack(L, n); else condmovestack(L);
+
+
+#define incr_top(L) {L->top++; luaD_checkstack(L,0);}
+
+#define savestack(L,p) ((char *)(p) - (char *)L->stack)
+#define restorestack(L,n) ((TValue *)((char *)L->stack + (n)))
+
+
+/* type of protected functions, to be ran by 'runprotected' */
+typedef void (*Pfunc) (lua_State *L, void *ud);
+
+LUAI_FUNC int luaD_protectedparser (lua_State *L, ZIO *z, const char *name,
+ const char *mode);
+LUAI_FUNC void luaD_hook (lua_State *L, int event, int line);
+LUAI_FUNC int luaD_precall (lua_State *L, StkId func, int nresults);
+LUAI_FUNC void luaD_call (lua_State *L, StkId func, int nResults,
+ int allowyield);
+LUAI_FUNC int luaD_pcall (lua_State *L, Pfunc func, void *u,
+ ptrdiff_t oldtop, ptrdiff_t ef);
+LUAI_FUNC int luaD_poscall (lua_State *L, StkId firstResult);
+LUAI_FUNC void luaD_reallocstack (lua_State *L, int newsize);
+LUAI_FUNC void luaD_growstack (lua_State *L, int n);
+LUAI_FUNC void luaD_shrinkstack (lua_State *L);
+
+LUAI_FUNC l_noret luaD_throw (lua_State *L, int errcode);
+LUAI_FUNC int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud);
+
+#endif
+
diff --git a/src/ldump.c b/src/ldump.c
new file mode 100644
index 0000000000..b6c7114f5d
--- /dev/null
+++ b/src/ldump.c
@@ -0,0 +1,214 @@
+/*
+** $Id: ldump.c,v 2.34 2014/11/02 19:19:04 roberto Exp $
+** save precompiled Lua chunks
+** See Copyright Notice in lua.h
+*/
+
+#define ldump_c
+#define LUA_CORE
+
+#include "lprefix.h"
+
+
+#include
+
+#include "lua.h"
+
+#include "lobject.h"
+#include "lstate.h"
+#include "lundump.h"
+
+
+typedef struct {
+ lua_State *L;
+ lua_Writer writer;
+ void *data;
+ int strip;
+ int status;
+} DumpState;
+
+
+/*
+** All high-level dumps go through DumpVector; you can change it to
+** change the endianness of the result
+*/
+#define DumpVector(v,n,D) DumpBlock(v,(n)*sizeof((v)[0]),D)
+
+#define DumpLiteral(s,D) DumpBlock(s, sizeof(s) - sizeof(char), D)
+
+
+static void DumpBlock (const void *b, size_t size, DumpState *D) {
+ if (D->status == 0) {
+ lua_unlock(D->L);
+ D->status = (*D->writer)(D->L, b, size, D->data);
+ lua_lock(D->L);
+ }
+}
+
+
+#define DumpVar(x,D) DumpVector(&x,1,D)
+
+
+static void DumpByte (int y, DumpState *D) {
+ lu_byte x = (lu_byte)y;
+ DumpVar(x, D);
+}
+
+
+static void DumpInt (int x, DumpState *D) {
+ DumpVar(x, D);
+}
+
+
+static void DumpNumber (lua_Number x, DumpState *D) {
+ DumpVar(x, D);
+}
+
+
+static void DumpInteger (lua_Integer x, DumpState *D) {
+ DumpVar(x, D);
+}
+
+
+static void DumpString (const TString *s, DumpState *D) {
+ if (s == NULL)
+ DumpByte(0, D);
+ else {
+ size_t size = s->len + 1; /* include trailing '\0' */
+ if (size < 0xFF)
+ DumpByte(cast_int(size), D);
+ else {
+ DumpByte(0xFF, D);
+ DumpVar(size, D);
+ }
+ DumpVector(getstr(s), size - 1, D); /* no need to save '\0' */
+ }
+}
+
+
+static void DumpCode (const Proto *f, DumpState *D) {
+ DumpInt(f->sizecode, D);
+ DumpVector(f->code, f->sizecode, D);
+}
+
+
+static void DumpFunction(const Proto *f, TString *psource, DumpState *D);
+
+static void DumpConstants (const Proto *f, DumpState *D) {
+ int i;
+ int n = f->sizek;
+ DumpInt(n, D);
+ for (i = 0; i < n; i++) {
+ const TValue *o = &f->k[i];
+ DumpByte(ttype(o), D);
+ switch (ttype(o)) {
+ case LUA_TNIL:
+ break;
+ case LUA_TBOOLEAN:
+ DumpByte(bvalue(o), D);
+ break;
+ case LUA_TNUMFLT:
+ DumpNumber(fltvalue(o), D);
+ break;
+ case LUA_TNUMINT:
+ DumpInteger(ivalue(o), D);
+ break;
+ case LUA_TSHRSTR:
+ case LUA_TLNGSTR:
+ DumpString(tsvalue(o), D);
+ break;
+ default:
+ lua_assert(0);
+ }
+ }
+}
+
+
+static void DumpProtos (const Proto *f, DumpState *D) {
+ int i;
+ int n = f->sizep;
+ DumpInt(n, D);
+ for (i = 0; i < n; i++)
+ DumpFunction(f->p[i], f->source, D);
+}
+
+
+static void DumpUpvalues (const Proto *f, DumpState *D) {
+ int i, n = f->sizeupvalues;
+ DumpInt(n, D);
+ for (i = 0; i < n; i++) {
+ DumpByte(f->upvalues[i].instack, D);
+ DumpByte(f->upvalues[i].idx, D);
+ }
+}
+
+
+static void DumpDebug (const Proto *f, DumpState *D) {
+ int i, n;
+ n = (D->strip) ? 0 : f->sizelineinfo;
+ DumpInt(n, D);
+ DumpVector(f->lineinfo, n, D);
+ n = (D->strip) ? 0 : f->sizelocvars;
+ DumpInt(n, D);
+ for (i = 0; i < n; i++) {
+ DumpString(f->locvars[i].varname, D);
+ DumpInt(f->locvars[i].startpc, D);
+ DumpInt(f->locvars[i].endpc, D);
+ }
+ n = (D->strip) ? 0 : f->sizeupvalues;
+ DumpInt(n, D);
+ for (i = 0; i < n; i++)
+ DumpString(f->upvalues[i].name, D);
+}
+
+
+static void DumpFunction (const Proto *f, TString *psource, DumpState *D) {
+ if (D->strip || f->source == psource)
+ DumpString(NULL, D); /* no debug info or same source as its parent */
+ else
+ DumpString(f->source, D);
+ DumpInt(f->linedefined, D);
+ DumpInt(f->lastlinedefined, D);
+ DumpByte(f->numparams, D);
+ DumpByte(f->is_vararg, D);
+ DumpByte(f->maxstacksize, D);
+ DumpCode(f, D);
+ DumpConstants(f, D);
+ DumpUpvalues(f, D);
+ DumpProtos(f, D);
+ DumpDebug(f, D);
+}
+
+
+static void DumpHeader (DumpState *D) {
+ DumpLiteral(LUA_SIGNATURE, D);
+ DumpByte(LUAC_VERSION, D);
+ DumpByte(LUAC_FORMAT, D);
+ DumpLiteral(LUAC_DATA, D);
+ DumpByte(sizeof(int), D);
+ DumpByte(sizeof(size_t), D);
+ DumpByte(sizeof(Instruction), D);
+ DumpByte(sizeof(lua_Integer), D);
+ DumpByte(sizeof(lua_Number), D);
+ DumpInteger(LUAC_INT, D);
+ DumpNumber(LUAC_NUM, D);
+}
+
+
+/*
+** dump Lua function as precompiled chunk
+*/
+int luaU_dump(lua_State *L, const Proto *f, lua_Writer w, void *data,
+ int strip) {
+ DumpState D;
+ D.L = L;
+ D.writer = w;
+ D.data = data;
+ D.strip = strip;
+ D.status = 0;
+ DumpHeader(&D);
+ DumpByte(f->sizeupvalues, &D);
+ DumpFunction(f, NULL, &D);
+ return D.status;
+}
+
diff --git a/src/lfunc.c b/src/lfunc.c
new file mode 100644
index 0000000000..67967dab3f
--- /dev/null
+++ b/src/lfunc.c
@@ -0,0 +1,151 @@
+/*
+** $Id: lfunc.c,v 2.45 2014/11/02 19:19:04 roberto Exp $
+** Auxiliary functions to manipulate prototypes and closures
+** See Copyright Notice in lua.h
+*/
+
+#define lfunc_c
+#define LUA_CORE
+
+#include "lprefix.h"
+
+
+#include
+
+#include "lua.h"
+
+#include "lfunc.h"
+#include "lgc.h"
+#include "lmem.h"
+#include "lobject.h"
+#include "lstate.h"
+
+
+
+CClosure *luaF_newCclosure (lua_State *L, int n) {
+ GCObject *o = luaC_newobj(L, LUA_TCCL, sizeCclosure(n));
+ CClosure *c = gco2ccl(o);
+ c->nupvalues = cast_byte(n);
+ return c;
+}
+
+
+LClosure *luaF_newLclosure (lua_State *L, int n) {
+ GCObject *o = luaC_newobj(L, LUA_TLCL, sizeLclosure(n));
+ LClosure *c = gco2lcl(o);
+ c->p = NULL;
+ c->nupvalues = cast_byte(n);
+ while (n--) c->upvals[n] = NULL;
+ return c;
+}
+
+/*
+** fill a closure with new closed upvalues
+*/
+void luaF_initupvals (lua_State *L, LClosure *cl) {
+ int i;
+ for (i = 0; i < cl->nupvalues; i++) {
+ UpVal *uv = luaM_new(L, UpVal);
+ uv->refcount = 1;
+ uv->v = &uv->u.value; /* make it closed */
+ setnilvalue(uv->v);
+ cl->upvals[i] = uv;
+ }
+}
+
+
+UpVal *luaF_findupval (lua_State *L, StkId level) {
+ UpVal **pp = &L->openupval;
+ UpVal *p;
+ UpVal *uv;
+ lua_assert(isintwups(L) || L->openupval == NULL);
+ while (*pp != NULL && (p = *pp)->v >= level) {
+ lua_assert(upisopen(p));
+ if (p->v == level) /* found a corresponding upvalue? */
+ return p; /* return it */
+ pp = &p->u.open.next;
+ }
+ /* not found: create a new upvalue */
+ uv = luaM_new(L, UpVal);
+ uv->refcount = 0;
+ uv->u.open.next = *pp; /* link it to list of open upvalues */
+ uv->u.open.touched = 1;
+ *pp = uv;
+ uv->v = level; /* current value lives in the stack */
+ if (!isintwups(L)) { /* thread not in list of threads with upvalues? */
+ L->twups = G(L)->twups; /* link it to the list */
+ G(L)->twups = L;
+ }
+ return uv;
+}
+
+
+void luaF_close (lua_State *L, StkId level) {
+ UpVal *uv;
+ while (L->openupval != NULL && (uv = L->openupval)->v >= level) {
+ lua_assert(upisopen(uv));
+ L->openupval = uv->u.open.next; /* remove from 'open' list */
+ if (uv->refcount == 0) /* no references? */
+ luaM_free(L, uv); /* free upvalue */
+ else {
+ setobj(L, &uv->u.value, uv->v); /* move value to upvalue slot */
+ uv->v = &uv->u.value; /* now current value lives here */
+ luaC_upvalbarrier(L, uv);
+ }
+ }
+}
+
+
+Proto *luaF_newproto (lua_State *L) {
+ GCObject *o = luaC_newobj(L, LUA_TPROTO, sizeof(Proto));
+ Proto *f = gco2p(o);
+ f->k = NULL;
+ f->sizek = 0;
+ f->p = NULL;
+ f->sizep = 0;
+ f->code = NULL;
+ f->cache = NULL;
+ f->sizecode = 0;
+ f->lineinfo = NULL;
+ f->sizelineinfo = 0;
+ f->upvalues = NULL;
+ f->sizeupvalues = 0;
+ f->numparams = 0;
+ f->is_vararg = 0;
+ f->maxstacksize = 0;
+ f->locvars = NULL;
+ f->sizelocvars = 0;
+ f->linedefined = 0;
+ f->lastlinedefined = 0;
+ f->source = NULL;
+ return f;
+}
+
+
+void luaF_freeproto (lua_State *L, Proto *f) {
+ luaM_freearray(L, f->code, f->sizecode);
+ luaM_freearray(L, f->p, f->sizep);
+ luaM_freearray(L, f->k, f->sizek);
+ luaM_freearray(L, f->lineinfo, f->sizelineinfo);
+ luaM_freearray(L, f->locvars, f->sizelocvars);
+ luaM_freearray(L, f->upvalues, f->sizeupvalues);
+ luaM_free(L, f);
+}
+
+
+/*
+** Look for n-th local variable at line 'line' in function 'func'.
+** Returns NULL if not found.
+*/
+const char *luaF_getlocalname (const Proto *f, int local_number, int pc) {
+ int i;
+ for (i = 0; isizelocvars && f->locvars[i].startpc <= pc; i++) {
+ if (pc < f->locvars[i].endpc) { /* is variable active? */
+ local_number--;
+ if (local_number == 0)
+ return getstr(f->locvars[i].varname);
+ }
+ }
+ return NULL; /* not found */
+}
+
diff --git a/src/lfunc.h b/src/lfunc.h
new file mode 100644
index 0000000000..256d3cf90b
--- /dev/null
+++ b/src/lfunc.h
@@ -0,0 +1,54 @@
+/*
+** $Id: lfunc.h,v 2.14 2014/06/19 18:27:20 roberto Exp $
+** Auxiliary functions to manipulate prototypes and closures
+** See Copyright Notice in lua.h
+*/
+
+#ifndef lfunc_h
+#define lfunc_h
+
+
+#include "lobject.h"
+
+
+#define sizeCclosure(n) (cast(int, sizeof(CClosure)) + \
+ cast(int, sizeof(TValue)*((n)-1)))
+
+#define sizeLclosure(n) (cast(int, sizeof(LClosure)) + \
+ cast(int, sizeof(TValue *)*((n)-1)))
+
+
+/* test whether thread is in 'twups' list */
+#define isintwups(L) (L->twups != L)
+
+
+/*
+** Upvalues for Lua closures
+*/
+struct UpVal {
+ TValue *v; /* points to stack or to its own value */
+ lu_mem refcount; /* reference counter */
+ union {
+ struct { /* (when open) */
+ UpVal *next; /* linked list */
+ int touched; /* mark to avoid cycles with dead threads */
+ } open;
+ TValue value; /* the value (when closed) */
+ } u;
+};
+
+#define upisopen(up) ((up)->v != &(up)->u.value)
+
+
+LUAI_FUNC Proto *luaF_newproto (lua_State *L);
+LUAI_FUNC CClosure *luaF_newCclosure (lua_State *L, int nelems);
+LUAI_FUNC LClosure *luaF_newLclosure (lua_State *L, int nelems);
+LUAI_FUNC void luaF_initupvals (lua_State *L, LClosure *cl);
+LUAI_FUNC UpVal *luaF_findupval (lua_State *L, StkId level);
+LUAI_FUNC void luaF_close (lua_State *L, StkId level);
+LUAI_FUNC void luaF_freeproto (lua_State *L, Proto *f);
+LUAI_FUNC const char *luaF_getlocalname (const Proto *func, int local_number,
+ int pc);
+
+
+#endif
diff --git a/src/lgc.c b/src/lgc.c
new file mode 100644
index 0000000000..8b95fb67da
--- /dev/null
+++ b/src/lgc.c
@@ -0,0 +1,1159 @@
+/*
+** $Id: lgc.c,v 2.201 2014/12/20 13:58:15 roberto Exp $
+** Garbage Collector
+** See Copyright Notice in lua.h
+*/
+
+#define lgc_c
+#define LUA_CORE
+
+#include "lprefix.h"
+
+
+#include
+
+#include "lua.h"
+
+#include "ldebug.h"
+#include "ldo.h"
+#include "lfunc.h"
+#include "lgc.h"
+#include "lmem.h"
+#include "lobject.h"
+#include "lstate.h"
+#include "lstring.h"
+#include "ltable.h"
+#include "ltm.h"
+
+
+/*
+** internal state for collector while inside the atomic phase. The
+** collector should never be in this state while running regular code.
+*/
+#define GCSinsideatomic (GCSpause + 1)
+
+/*
+** cost of sweeping one element (the size of a small object divided
+** by some adjust for the sweep speed)
+*/
+#define GCSWEEPCOST ((sizeof(TString) + 4) / 4)
+
+/* maximum number of elements to sweep in each single step */
+#define GCSWEEPMAX (cast_int((GCSTEPSIZE / GCSWEEPCOST) / 4))
+
+/* cost of calling one finalizer */
+#define GCFINALIZECOST GCSWEEPCOST
+
+
+/*
+** macro to adjust 'stepmul': 'stepmul' is actually used like
+** 'stepmul / STEPMULADJ' (value chosen by tests)
+*/
+#define STEPMULADJ 200
+
+
+/*
+** macro to adjust 'pause': 'pause' is actually used like
+** 'pause / PAUSEADJ' (value chosen by tests)
+*/
+#define PAUSEADJ 100
+
+
+/*
+** 'makewhite' erases all color bits then sets only the current white
+** bit
+*/
+#define maskcolors (~(bitmask(BLACKBIT) | WHITEBITS))
+#define makewhite(g,x) \
+ (x->marked = cast_byte((x->marked & maskcolors) | luaC_white(g)))
+
+#define white2gray(x) resetbits(x->marked, WHITEBITS)
+#define black2gray(x) resetbit(x->marked, BLACKBIT)
+
+
+#define valiswhite(x) (iscollectable(x) && iswhite(gcvalue(x)))
+
+#define checkdeadkey(n) lua_assert(!ttisdeadkey(gkey(n)) || ttisnil(gval(n)))
+
+
+#define checkconsistency(obj) \
+ lua_longassert(!iscollectable(obj) || righttt(obj))
+
+
+#define markvalue(g,o) { checkconsistency(o); \
+ if (valiswhite(o)) reallymarkobject(g,gcvalue(o)); }
+
+#define markobject(g,t) \
+ { if ((t) && iswhite(t)) reallymarkobject(g, obj2gco(t)); }
+
+static void reallymarkobject (global_State *g, GCObject *o);
+
+
+/*
+** {======================================================
+** Generic functions
+** =======================================================
+*/
+
+
+/*
+** one after last element in a hash array
+*/
+#define gnodelast(h) gnode(h, cast(size_t, sizenode(h)))
+
+
+/*
+** link collectable object 'o' into list pointed by 'p'
+*/
+#define linkgclist(o,p) ((o)->gclist = (p), (p) = obj2gco(o))
+
+
+/*
+** if key is not marked, mark its entry as dead (therefore removing it
+** from the table)
+*/
+static void removeentry (Node *n) {
+ lua_assert(ttisnil(gval(n)));
+ if (valiswhite(gkey(n)))
+ setdeadvalue(wgkey(n)); /* unused and unmarked key; remove it */
+}
+
+
+/*
+** tells whether a key or value can be cleared from a weak
+** table. Non-collectable objects are never removed from weak
+** tables. Strings behave as 'values', so are never removed too. for
+** other objects: if really collected, cannot keep them; for objects
+** being finalized, keep them in keys, but not in values
+*/
+static int iscleared (global_State *g, const TValue *o) {
+ if (!iscollectable(o)) return 0;
+ else if (ttisstring(o)) {
+ markobject(g, tsvalue(o)); /* strings are 'values', so are never weak */
+ return 0;
+ }
+ else return iswhite(gcvalue(o));
+}
+
+
+/*
+** barrier that moves collector forward, that is, mark the white object
+** being pointed by a black object. (If in sweep phase, clear the black
+** object to white [sweep it] to avoid other barrier calls for this
+** same object.)
+*/
+void luaC_barrier_ (lua_State *L, GCObject *o, GCObject *v) {
+ global_State *g = G(L);
+ lua_assert(isblack(o) && iswhite(v) && !isdead(g, v) && !isdead(g, o));
+ if (keepinvariant(g)) /* must keep invariant? */
+ reallymarkobject(g, v); /* restore invariant */
+ else { /* sweep phase */
+ lua_assert(issweepphase(g));
+ makewhite(g, o); /* mark main obj. as white to avoid other barriers */
+ }
+}
+
+
+/*
+** barrier that moves collector backward, that is, mark the black object
+** pointing to a white object as gray again.
+*/
+void luaC_barrierback_ (lua_State *L, Table *t) {
+ global_State *g = G(L);
+ lua_assert(isblack(t) && !isdead(g, t));
+ black2gray(t); /* make table gray (again) */
+ linkgclist(t, g->grayagain);
+}
+
+
+/*
+** barrier for assignments to closed upvalues. Because upvalues are
+** shared among closures, it is impossible to know the color of all
+** closures pointing to it. So, we assume that the object being assigned
+** must be marked.
+*/
+void luaC_upvalbarrier_ (lua_State *L, UpVal *uv) {
+ global_State *g = G(L);
+ GCObject *o = gcvalue(uv->v);
+ lua_assert(!upisopen(uv)); /* ensured by macro luaC_upvalbarrier */
+ if (keepinvariant(g))
+ markobject(g, o);
+}
+
+
+void luaC_fix (lua_State *L, GCObject *o) {
+ global_State *g = G(L);
+ lua_assert(g->allgc == o); /* object must be 1st in 'allgc' list! */
+ white2gray(o); /* they will be gray forever */
+ g->allgc = o->next; /* remove object from 'allgc' list */
+ o->next = g->fixedgc; /* link it to 'fixedgc' list */
+ g->fixedgc = o;
+}
+
+
+/*
+** create a new collectable object (with given type and size) and link
+** it to 'allgc' list.
+*/
+GCObject *luaC_newobj (lua_State *L, int tt, size_t sz) {
+ global_State *g = G(L);
+ GCObject *o = cast(GCObject *, luaM_newobject(L, novariant(tt), sz));
+ o->marked = luaC_white(g);
+ o->tt = tt;
+ o->next = g->allgc;
+ g->allgc = o;
+ return o;
+}
+
+/* }====================================================== */
+
+
+
+/*
+** {======================================================
+** Mark functions
+** =======================================================
+*/
+
+
+/*
+** mark an object. Userdata, strings, and closed upvalues are visited
+** and turned black here. Other objects are marked gray and added
+** to appropriate list to be visited (and turned black) later. (Open
+** upvalues are already linked in 'headuv' list.)
+*/
+static void reallymarkobject (global_State *g, GCObject *o) {
+ reentry:
+ white2gray(o);
+ switch (o->tt) {
+ case LUA_TSHRSTR:
+ case LUA_TLNGSTR: {
+ gray2black(o);
+ g->GCmemtrav += sizestring(gco2ts(o));
+ break;
+ }
+ case LUA_TUSERDATA: {
+ TValue uvalue;
+ markobject(g, gco2u(o)->metatable); /* mark its metatable */
+ gray2black(o);
+ g->GCmemtrav += sizeudata(gco2u(o));
+ getuservalue(g->mainthread, gco2u(o), &uvalue);
+ if (valiswhite(&uvalue)) { /* markvalue(g, &uvalue); */
+ o = gcvalue(&uvalue);
+ goto reentry;
+ }
+ break;
+ }
+ case LUA_TLCL: {
+ linkgclist(gco2lcl(o), g->gray);
+ break;
+ }
+ case LUA_TCCL: {
+ linkgclist(gco2ccl(o), g->gray);
+ break;
+ }
+ case LUA_TTABLE: {
+ linkgclist(gco2t(o), g->gray);
+ break;
+ }
+ case LUA_TTHREAD: {
+ linkgclist(gco2th(o), g->gray);
+ break;
+ }
+ case LUA_TPROTO: {
+ linkgclist(gco2p(o), g->gray);
+ break;
+ }
+ default: lua_assert(0); break;
+ }
+}
+
+
+/*
+** mark metamethods for basic types
+*/
+static void markmt (global_State *g) {
+ int i;
+ for (i=0; i < LUA_NUMTAGS; i++)
+ markobject(g, g->mt[i]);
+}
+
+
+/*
+** mark all objects in list of being-finalized
+*/
+static void markbeingfnz (global_State *g) {
+ GCObject *o;
+ for (o = g->tobefnz; o != NULL; o = o->next)
+ markobject(g, o);
+}
+
+
+/*
+** Mark all values stored in marked open upvalues from non-marked threads.
+** (Values from marked threads were already marked when traversing the
+** thread.) Remove from the list threads that no longer have upvalues and
+** not-marked threads.
+*/
+static void remarkupvals (global_State *g) {
+ lua_State *thread;
+ lua_State **p = &g->twups;
+ while ((thread = *p) != NULL) {
+ lua_assert(!isblack(thread)); /* threads are never black */
+ if (isgray(thread) && thread->openupval != NULL)
+ p = &thread->twups; /* keep marked thread with upvalues in the list */
+ else { /* thread is not marked or without upvalues */
+ UpVal *uv;
+ *p = thread->twups; /* remove thread from the list */
+ thread->twups = thread; /* mark that it is out of list */
+ for (uv = thread->openupval; uv != NULL; uv = uv->u.open.next) {
+ if (uv->u.open.touched) {
+ markvalue(g, uv->v); /* remark upvalue's value */
+ uv->u.open.touched = 0;
+ }
+ }
+ }
+ }
+}
+
+
+/*
+** mark root set and reset all gray lists, to start a new collection
+*/
+static void restartcollection (global_State *g) {
+ g->gray = g->grayagain = NULL;
+ g->weak = g->allweak = g->ephemeron = NULL;
+ markobject(g, g->mainthread);
+ markvalue(g, &g->l_registry);
+ markmt(g);
+ markbeingfnz(g); /* mark any finalizing object left from previous cycle */
+}
+
+/* }====================================================== */
+
+
+/*
+** {======================================================
+** Traverse functions
+** =======================================================
+*/
+
+/*
+** Traverse a table with weak values and link it to proper list. During
+** propagate phase, keep it in 'grayagain' list, to be revisited in the
+** atomic phase. In the atomic phase, if table has any white value,
+** put it in 'weak' list, to be cleared.
+*/
+static void traverseweakvalue (global_State *g, Table *h) {
+ Node *n, *limit = gnodelast(h);
+ /* if there is array part, assume it may have white values (it is not
+ worth traversing it now just to check) */
+ int hasclears = (h->sizearray > 0);
+ for (n = gnode(h, 0); n < limit; n++) { /* traverse hash part */
+ checkdeadkey(n);
+ if (ttisnil(gval(n))) /* entry is empty? */
+ removeentry(n); /* remove it */
+ else {
+ lua_assert(!ttisnil(gkey(n)));
+ markvalue(g, gkey(n)); /* mark key */
+ if (!hasclears && iscleared(g, gval(n))) /* is there a white value? */
+ hasclears = 1; /* table will have to be cleared */
+ }
+ }
+ if (g->gcstate == GCSpropagate)
+ linkgclist(h, g->grayagain); /* must retraverse it in atomic phase */
+ else if (hasclears)
+ linkgclist(h, g->weak); /* has to be cleared later */
+}
+
+
+/*
+** Traverse an ephemeron table and link it to proper list. Returns true
+** iff any object was marked during this traversal (which implies that
+** convergence has to continue). During propagation phase, keep table
+** in 'grayagain' list, to be visited again in the atomic phase. In
+** the atomic phase, if table has any white->white entry, it has to
+** be revisited during ephemeron convergence (as that key may turn
+** black). Otherwise, if it has any white key, table has to be cleared
+** (in the atomic phase).
+*/
+static int traverseephemeron (global_State *g, Table *h) {
+ int marked = 0; /* true if an object is marked in this traversal */
+ int hasclears = 0; /* true if table has white keys */
+ int hasww = 0; /* true if table has entry "white-key -> white-value" */
+ Node *n, *limit = gnodelast(h);
+ unsigned int i;
+ /* traverse array part */
+ for (i = 0; i < h->sizearray; i++) {
+ if (valiswhite(&h->array[i])) {
+ marked = 1;
+ reallymarkobject(g, gcvalue(&h->array[i]));
+ }
+ }
+ /* traverse hash part */
+ for (n = gnode(h, 0); n < limit; n++) {
+ checkdeadkey(n);
+ if (ttisnil(gval(n))) /* entry is empty? */
+ removeentry(n); /* remove it */
+ else if (iscleared(g, gkey(n))) { /* key is not marked (yet)? */
+ hasclears = 1; /* table must be cleared */
+ if (valiswhite(gval(n))) /* value not marked yet? */
+ hasww = 1; /* white-white entry */
+ }
+ else if (valiswhite(gval(n))) { /* value not marked yet? */
+ marked = 1;
+ reallymarkobject(g, gcvalue(gval(n))); /* mark it now */
+ }
+ }
+ /* link table into proper list */
+ if (g->gcstate == GCSpropagate)
+ linkgclist(h, g->grayagain); /* must retraverse it in atomic phase */
+ else if (hasww) /* table has white->white entries? */
+ linkgclist(h, g->ephemeron); /* have to propagate again */
+ else if (hasclears) /* table has white keys? */
+ linkgclist(h, g->allweak); /* may have to clean white keys */
+ return marked;
+}
+
+
+static void traversestrongtable (global_State *g, Table *h) {
+ Node *n, *limit = gnodelast(h);
+ unsigned int i;
+ for (i = 0; i < h->sizearray; i++) /* traverse array part */
+ markvalue(g, &h->array[i]);
+ for (n = gnode(h, 0); n < limit; n++) { /* traverse hash part */
+ checkdeadkey(n);
+ if (ttisnil(gval(n))) /* entry is empty? */
+ removeentry(n); /* remove it */
+ else {
+ lua_assert(!ttisnil(gkey(n)));
+ markvalue(g, gkey(n)); /* mark key */
+ markvalue(g, gval(n)); /* mark value */
+ }
+ }
+}
+
+
+static lu_mem traversetable (global_State *g, Table *h) {
+ const char *weakkey, *weakvalue;
+ const TValue *mode = gfasttm(g, h->metatable, TM_MODE);
+ markobject(g, h->metatable);
+ if (mode && ttisstring(mode) && /* is there a weak mode? */
+ ((weakkey = strchr(svalue(mode), 'k')),
+ (weakvalue = strchr(svalue(mode), 'v')),
+ (weakkey || weakvalue))) { /* is really weak? */
+ black2gray(h); /* keep table gray */
+ if (!weakkey) /* strong keys? */
+ traverseweakvalue(g, h);
+ else if (!weakvalue) /* strong values? */
+ traverseephemeron(g, h);
+ else /* all weak */
+ linkgclist(h, g->allweak); /* nothing to traverse now */
+ }
+ else /* not weak */
+ traversestrongtable(g, h);
+ return sizeof(Table) + sizeof(TValue) * h->sizearray +
+ sizeof(Node) * cast(size_t, sizenode(h));
+}
+
+
+static int traverseproto (global_State *g, Proto *f) {
+ int i;
+ if (f->cache && iswhite(f->cache))
+ f->cache = NULL; /* allow cache to be collected */
+ markobject(g, f->source);
+ for (i = 0; i < f->sizek; i++) /* mark literals */
+ markvalue(g, &f->k[i]);
+ for (i = 0; i < f->sizeupvalues; i++) /* mark upvalue names */
+ markobject(g, f->upvalues[i].name);
+ for (i = 0; i < f->sizep; i++) /* mark nested protos */
+ markobject(g, f->p[i]);
+ for (i = 0; i < f->sizelocvars; i++) /* mark local-variable names */
+ markobject(g, f->locvars[i].varname);
+ return sizeof(Proto) + sizeof(Instruction) * f->sizecode +
+ sizeof(Proto *) * f->sizep +
+ sizeof(TValue) * f->sizek +
+ sizeof(int) * f->sizelineinfo +
+ sizeof(LocVar) * f->sizelocvars +
+ sizeof(Upvaldesc) * f->sizeupvalues;
+}
+
+
+static lu_mem traverseCclosure (global_State *g, CClosure *cl) {
+ int i;
+ for (i = 0; i < cl->nupvalues; i++) /* mark its upvalues */
+ markvalue(g, &cl->upvalue[i]);
+ return sizeCclosure(cl->nupvalues);
+}
+
+/*
+** open upvalues point to values in a thread, so those values should
+** be marked when the thread is traversed except in the atomic phase
+** (because then the value cannot be changed by the thread and the
+** thread may not be traversed again)
+*/
+static lu_mem traverseLclosure (global_State *g, LClosure *cl) {
+ int i;
+ markobject(g, cl->p); /* mark its prototype */
+ for (i = 0; i < cl->nupvalues; i++) { /* mark its upvalues */
+ UpVal *uv = cl->upvals[i];
+ if (uv != NULL) {
+ if (upisopen(uv) && g->gcstate != GCSinsideatomic)
+ uv->u.open.touched = 1; /* can be marked in 'remarkupvals' */
+ else
+ markvalue(g, uv->v);
+ }
+ }
+ return sizeLclosure(cl->nupvalues);
+}
+
+
+static lu_mem traversethread (global_State *g, lua_State *th) {
+ StkId o = th->stack;
+ if (o == NULL)
+ return 1; /* stack not completely built yet */
+ lua_assert(g->gcstate == GCSinsideatomic ||
+ th->openupval == NULL || isintwups(th));
+ for (; o < th->top; o++) /* mark live elements in the stack */
+ markvalue(g, o);
+ if (g->gcstate == GCSinsideatomic) { /* final traversal? */
+ StkId lim = th->stack + th->stacksize; /* real end of stack */
+ for (; o < lim; o++) /* clear not-marked stack slice */
+ setnilvalue(o);
+ /* 'remarkupvals' may have removed thread from 'twups' list */
+ if (!isintwups(th) && th->openupval != NULL) {
+ th->twups = g->twups; /* link it back to the list */
+ g->twups = th;
+ }
+ }
+ else if (g->gckind != KGC_EMERGENCY)
+ luaD_shrinkstack(th); /* do not change stack in emergency cycle */
+ return (sizeof(lua_State) + sizeof(TValue) * th->stacksize);
+}
+
+
+/*
+** traverse one gray object, turning it to black (except for threads,
+** which are always gray).
+*/
+static void propagatemark (global_State *g) {
+ lu_mem size;
+ GCObject *o = g->gray;
+ lua_assert(isgray(o));
+ gray2black(o);
+ switch (o->tt) {
+ case LUA_TTABLE: {
+ Table *h = gco2t(o);
+ g->gray = h->gclist; /* remove from 'gray' list */
+ size = traversetable(g, h);
+ break;
+ }
+ case LUA_TLCL: {
+ LClosure *cl = gco2lcl(o);
+ g->gray = cl->gclist; /* remove from 'gray' list */
+ size = traverseLclosure(g, cl);
+ break;
+ }
+ case LUA_TCCL: {
+ CClosure *cl = gco2ccl(o);
+ g->gray = cl->gclist; /* remove from 'gray' list */
+ size = traverseCclosure(g, cl);
+ break;
+ }
+ case LUA_TTHREAD: {
+ lua_State *th = gco2th(o);
+ g->gray = th->gclist; /* remove from 'gray' list */
+ linkgclist(th, g->grayagain); /* insert into 'grayagain' list */
+ black2gray(o);
+ size = traversethread(g, th);
+ break;
+ }
+ case LUA_TPROTO: {
+ Proto *p = gco2p(o);
+ g->gray = p->gclist; /* remove from 'gray' list */
+ size = traverseproto(g, p);
+ break;
+ }
+ default: lua_assert(0); return;
+ }
+ g->GCmemtrav += size;
+}
+
+
+static void propagateall (global_State *g) {
+ while (g->gray) propagatemark(g);
+}
+
+
+static void convergeephemerons (global_State *g) {
+ int changed;
+ do {
+ GCObject *w;
+ GCObject *next = g->ephemeron; /* get ephemeron list */
+ g->ephemeron = NULL; /* tables may return to this list when traversed */
+ changed = 0;
+ while ((w = next) != NULL) {
+ next = gco2t(w)->gclist;
+ if (traverseephemeron(g, gco2t(w))) { /* traverse marked some value? */
+ propagateall(g); /* propagate changes */
+ changed = 1; /* will have to revisit all ephemeron tables */
+ }
+ }
+ } while (changed);
+}
+
+/* }====================================================== */
+
+
+/*
+** {======================================================
+** Sweep Functions
+** =======================================================
+*/
+
+
+/*
+** clear entries with unmarked keys from all weaktables in list 'l' up
+** to element 'f'
+*/
+static void clearkeys (global_State *g, GCObject *l, GCObject *f) {
+ for (; l != f; l = gco2t(l)->gclist) {
+ Table *h = gco2t(l);
+ Node *n, *limit = gnodelast(h);
+ for (n = gnode(h, 0); n < limit; n++) {
+ if (!ttisnil(gval(n)) && (iscleared(g, gkey(n)))) {
+ setnilvalue(gval(n)); /* remove value ... */
+ removeentry(n); /* and remove entry from table */
+ }
+ }
+ }
+}
+
+
+/*
+** clear entries with unmarked values from all weaktables in list 'l' up
+** to element 'f'
+*/
+static void clearvalues (global_State *g, GCObject *l, GCObject *f) {
+ for (; l != f; l = gco2t(l)->gclist) {
+ Table *h = gco2t(l);
+ Node *n, *limit = gnodelast(h);
+ unsigned int i;
+ for (i = 0; i < h->sizearray; i++) {
+ TValue *o = &h->array[i];
+ if (iscleared(g, o)) /* value was collected? */
+ setnilvalue(o); /* remove value */
+ }
+ for (n = gnode(h, 0); n < limit; n++) {
+ if (!ttisnil(gval(n)) && iscleared(g, gval(n))) {
+ setnilvalue(gval(n)); /* remove value ... */
+ removeentry(n); /* and remove entry from table */
+ }
+ }
+ }
+}
+
+
+void luaC_upvdeccount (lua_State *L, UpVal *uv) {
+ lua_assert(uv->refcount > 0);
+ uv->refcount--;
+ if (uv->refcount == 0 && !upisopen(uv))
+ luaM_free(L, uv);
+}
+
+
+static void freeLclosure (lua_State *L, LClosure *cl) {
+ int i;
+ for (i = 0; i < cl->nupvalues; i++) {
+ UpVal *uv = cl->upvals[i];
+ if (uv)
+ luaC_upvdeccount(L, uv);
+ }
+ luaM_freemem(L, cl, sizeLclosure(cl->nupvalues));
+}
+
+
+static void freeobj (lua_State *L, GCObject *o) {
+ switch (o->tt) {
+ case LUA_TPROTO: luaF_freeproto(L, gco2p(o)); break;
+ case LUA_TLCL: {
+ freeLclosure(L, gco2lcl(o));
+ break;
+ }
+ case LUA_TCCL: {
+ luaM_freemem(L, o, sizeCclosure(gco2ccl(o)->nupvalues));
+ break;
+ }
+ case LUA_TTABLE: luaH_free(L, gco2t(o)); break;
+ case LUA_TTHREAD: luaE_freethread(L, gco2th(o)); break;
+ case LUA_TUSERDATA: luaM_freemem(L, o, sizeudata(gco2u(o))); break;
+ case LUA_TSHRSTR:
+ luaS_remove(L, gco2ts(o)); /* remove it from hash table */
+ /* go through */
+ case LUA_TLNGSTR: {
+ luaM_freemem(L, o, sizestring(gco2ts(o)));
+ break;
+ }
+ default: lua_assert(0);
+ }
+}
+
+
+#define sweepwholelist(L,p) sweeplist(L,p,MAX_LUMEM)
+static GCObject **sweeplist (lua_State *L, GCObject **p, lu_mem count);
+
+
+/*
+** sweep at most 'count' elements from a list of GCObjects erasing dead
+** objects, where a dead object is one marked with the old (non current)
+** white; change all non-dead objects back to white, preparing for next
+** collection cycle. Return where to continue the traversal or NULL if
+** list is finished.
+*/
+static GCObject **sweeplist (lua_State *L, GCObject **p, lu_mem count) {
+ global_State *g = G(L);
+ int ow = otherwhite(g);
+ int white = luaC_white(g); /* current white */
+ while (*p != NULL && count-- > 0) {
+ GCObject *curr = *p;
+ int marked = curr->marked;
+ if (isdeadm(ow, marked)) { /* is 'curr' dead? */
+ *p = curr->next; /* remove 'curr' from list */
+ freeobj(L, curr); /* erase 'curr' */
+ }
+ else { /* change mark to 'white' */
+ curr->marked = cast_byte((marked & maskcolors) | white);
+ p = &curr->next; /* go to next element */
+ }
+ }
+ return (*p == NULL) ? NULL : p;
+}
+
+
+/*
+** sweep a list until a live object (or end of list)
+*/
+static GCObject **sweeptolive (lua_State *L, GCObject **p, int *n) {
+ GCObject **old = p;
+ int i = 0;
+ do {
+ i++;
+ p = sweeplist(L, p, 1);
+ } while (p == old);
+ if (n) *n += i;
+ return p;
+}
+
+/* }====================================================== */
+
+
+/*
+** {======================================================
+** Finalization
+** =======================================================
+*/
+
+/*
+** If possible, free concatenation buffer and shrink string table
+*/
+static void checkSizes (lua_State *L, global_State *g) {
+ if (g->gckind != KGC_EMERGENCY) {
+ l_mem olddebt = g->GCdebt;
+ luaZ_freebuffer(L, &g->buff); /* free concatenation buffer */
+ if (g->strt.nuse < g->strt.size / 4) /* string table too big? */
+ luaS_resize(L, g->strt.size / 2); /* shrink it a little */
+ g->GCestimate += g->GCdebt - olddebt; /* update estimate */
+ }
+}
+
+
+static GCObject *udata2finalize (global_State *g) {
+ GCObject *o = g->tobefnz; /* get first element */
+ lua_assert(tofinalize(o));
+ g->tobefnz = o->next; /* remove it from 'tobefnz' list */
+ o->next = g->allgc; /* return it to 'allgc' list */
+ g->allgc = o;
+ resetbit(o->marked, FINALIZEDBIT); /* object is "normal" again */
+ if (issweepphase(g))
+ makewhite(g, o); /* "sweep" object */
+ return o;
+}
+
+
+static void dothecall (lua_State *L, void *ud) {
+ UNUSED(ud);
+ luaD_call(L, L->top - 2, 0, 0);
+}
+
+
+static void GCTM (lua_State *L, int propagateerrors) {
+ global_State *g = G(L);
+ const TValue *tm;
+ TValue v;
+ setgcovalue(L, &v, udata2finalize(g));
+ tm = luaT_gettmbyobj(L, &v, TM_GC);
+ if (tm != NULL && ttisfunction(tm)) { /* is there a finalizer? */
+ int status;
+ lu_byte oldah = L->allowhook;
+ int running = g->gcrunning;
+ L->allowhook = 0; /* stop debug hooks during GC metamethod */
+ g->gcrunning = 0; /* avoid GC steps */
+ setobj2s(L, L->top, tm); /* push finalizer... */
+ setobj2s(L, L->top + 1, &v); /* ... and its argument */
+ L->top += 2; /* and (next line) call the finalizer */
+ status = luaD_pcall(L, dothecall, NULL, savestack(L, L->top - 2), 0);
+ L->allowhook = oldah; /* restore hooks */
+ g->gcrunning = running; /* restore state */
+ if (status != LUA_OK && propagateerrors) { /* error while running __gc? */
+ if (status == LUA_ERRRUN) { /* is there an error object? */
+ const char *msg = (ttisstring(L->top - 1))
+ ? svalue(L->top - 1)
+ : "no message";
+ luaO_pushfstring(L, "error in __gc metamethod (%s)", msg);
+ status = LUA_ERRGCMM; /* error in __gc metamethod */
+ }
+ luaD_throw(L, status); /* re-throw error */
+ }
+ }
+}
+
+
+/*
+** call a few (up to 'g->gcfinnum') finalizers
+*/
+static int runafewfinalizers (lua_State *L) {
+ global_State *g = G(L);
+ unsigned int i;
+ lua_assert(!g->tobefnz || g->gcfinnum > 0);
+ for (i = 0; g->tobefnz && i < g->gcfinnum; i++)
+ GCTM(L, 1); /* call one finalizer */
+ g->gcfinnum = (!g->tobefnz) ? 0 /* nothing more to finalize? */
+ : g->gcfinnum * 2; /* else call a few more next time */
+ return i;
+}
+
+
+/*
+** call all pending finalizers
+*/
+static void callallpendingfinalizers (lua_State *L, int propagateerrors) {
+ global_State *g = G(L);
+ while (g->tobefnz)
+ GCTM(L, propagateerrors);
+}
+
+
+/*
+** find last 'next' field in list 'p' list (to add elements in its end)
+*/
+static GCObject **findlast (GCObject **p) {
+ while (*p != NULL)
+ p = &(*p)->next;
+ return p;
+}
+
+
+/*
+** move all unreachable objects (or 'all' objects) that need
+** finalization from list 'finobj' to list 'tobefnz' (to be finalized)
+*/
+static void separatetobefnz (global_State *g, int all) {
+ GCObject *curr;
+ GCObject **p = &g->finobj;
+ GCObject **lastnext = findlast(&g->tobefnz);
+ while ((curr = *p) != NULL) { /* traverse all finalizable objects */
+ lua_assert(tofinalize(curr));
+ if (!(iswhite(curr) || all)) /* not being collected? */
+ p = &curr->next; /* don't bother with it */
+ else {
+ *p = curr->next; /* remove 'curr' from 'finobj' list */
+ curr->next = *lastnext; /* link at the end of 'tobefnz' list */
+ *lastnext = curr;
+ lastnext = &curr->next;
+ }
+ }
+}
+
+
+/*
+** if object 'o' has a finalizer, remove it from 'allgc' list (must
+** search the list to find it) and link it in 'finobj' list.
+*/
+void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt) {
+ global_State *g = G(L);
+ if (tofinalize(o) || /* obj. is already marked... */
+ gfasttm(g, mt, TM_GC) == NULL) /* or has no finalizer? */
+ return; /* nothing to be done */
+ else { /* move 'o' to 'finobj' list */
+ GCObject **p;
+ if (issweepphase(g)) {
+ makewhite(g, o); /* "sweep" object 'o' */
+ if (g->sweepgc == &o->next) /* should not remove 'sweepgc' object */
+ g->sweepgc = sweeptolive(L, g->sweepgc, NULL); /* change 'sweepgc' */
+ }
+ /* search for pointer pointing to 'o' */
+ for (p = &g->allgc; *p != o; p = &(*p)->next) { /* empty */ }
+ *p = o->next; /* remove 'o' from 'allgc' list */
+ o->next = g->finobj; /* link it in 'finobj' list */
+ g->finobj = o;
+ l_setbit(o->marked, FINALIZEDBIT); /* mark it as such */
+ }
+}
+
+/* }====================================================== */
+
+
+
+/*
+** {======================================================
+** GC control
+** =======================================================
+*/
+
+
+/*
+** Set a reasonable "time" to wait before starting a new GC cycle; cycle
+** will start when memory use hits threshold. (Division by 'estimate'
+** should be OK: it cannot be zero (because Lua cannot even start with
+** less than PAUSEADJ bytes).
+*/
+static void setpause (global_State *g) {
+ l_mem threshold, debt;
+ l_mem estimate = g->GCestimate / PAUSEADJ; /* adjust 'estimate' */
+ lua_assert(estimate > 0);
+ threshold = (g->gcpause < MAX_LMEM / estimate) /* overflow? */
+ ? estimate * g->gcpause /* no overflow */
+ : MAX_LMEM; /* overflow; truncate to maximum */
+ debt = gettotalbytes(g) - threshold;
+ luaE_setdebt(g, debt);
+}
+
+
+/*
+** Enter first sweep phase.
+** The call to 'sweeptolive' makes pointer point to an object inside
+** the list (instead of to the header), so that the real sweep do not
+** need to skip objects created between "now" and the start of the real
+** sweep.
+** Returns how many objects it swept.
+*/
+static int entersweep (lua_State *L) {
+ global_State *g = G(L);
+ int n = 0;
+ g->gcstate = GCSswpallgc;
+ lua_assert(g->sweepgc == NULL);
+ g->sweepgc = sweeptolive(L, &g->allgc, &n);
+ return n;
+}
+
+
+void luaC_freeallobjects (lua_State *L) {
+ global_State *g = G(L);
+ separatetobefnz(g, 1); /* separate all objects with finalizers */
+ lua_assert(g->finobj == NULL);
+ callallpendingfinalizers(L, 0);
+ lua_assert(g->tobefnz == NULL);
+ g->currentwhite = WHITEBITS; /* this "white" makes all objects look dead */
+ g->gckind = KGC_NORMAL;
+ sweepwholelist(L, &g->finobj);
+ sweepwholelist(L, &g->allgc);
+ sweepwholelist(L, &g->fixedgc); /* collect fixed objects */
+ lua_assert(g->strt.nuse == 0);
+}
+
+
+static l_mem atomic (lua_State *L) {
+ global_State *g = G(L);
+ l_mem work;
+ GCObject *origweak, *origall;
+ GCObject *grayagain = g->grayagain; /* save original list */
+ lua_assert(g->ephemeron == NULL && g->weak == NULL);
+ lua_assert(!iswhite(g->mainthread));
+ g->gcstate = GCSinsideatomic;
+ g->GCmemtrav = 0; /* start counting work */
+ markobject(g, L); /* mark running thread */
+ /* registry and global metatables may be changed by API */
+ markvalue(g, &g->l_registry);
+ markmt(g); /* mark global metatables */
+ /* remark occasional upvalues of (maybe) dead threads */
+ remarkupvals(g);
+ propagateall(g); /* propagate changes */
+ work = g->GCmemtrav; /* stop counting (do not recount 'grayagain') */
+ g->gray = grayagain;
+ propagateall(g); /* traverse 'grayagain' list */
+ g->GCmemtrav = 0; /* restart counting */
+ convergeephemerons(g);
+ /* at this point, all strongly accessible objects are marked. */
+ /* Clear values from weak tables, before checking finalizers */
+ clearvalues(g, g->weak, NULL);
+ clearvalues(g, g->allweak, NULL);
+ origweak = g->weak; origall = g->allweak;
+ work += g->GCmemtrav; /* stop counting (objects being finalized) */
+ separatetobefnz(g, 0); /* separate objects to be finalized */
+ g->gcfinnum = 1; /* there may be objects to be finalized */
+ markbeingfnz(g); /* mark objects that will be finalized */
+ propagateall(g); /* remark, to propagate 'resurrection' */
+ g->GCmemtrav = 0; /* restart counting */
+ convergeephemerons(g);
+ /* at this point, all resurrected objects are marked. */
+ /* remove dead objects from weak tables */
+ clearkeys(g, g->ephemeron, NULL); /* clear keys from all ephemeron tables */
+ clearkeys(g, g->allweak, NULL); /* clear keys from all 'allweak' tables */
+ /* clear values from resurrected weak tables */
+ clearvalues(g, g->weak, origweak);
+ clearvalues(g, g->allweak, origall);
+ g->currentwhite = cast_byte(otherwhite(g)); /* flip current white */
+ work += g->GCmemtrav; /* complete counting */
+ return work; /* estimate of memory marked by 'atomic' */
+}
+
+
+static lu_mem sweepstep (lua_State *L, global_State *g,
+ int nextstate, GCObject **nextlist) {
+ if (g->sweepgc) {
+ l_mem olddebt = g->GCdebt;
+ g->sweepgc = sweeplist(L, g->sweepgc, GCSWEEPMAX);
+ g->GCestimate += g->GCdebt - olddebt; /* update estimate */
+ if (g->sweepgc) /* is there still something to sweep? */
+ return (GCSWEEPMAX * GCSWEEPCOST);
+ }
+ /* else enter next state */
+ g->gcstate = nextstate;
+ g->sweepgc = nextlist;
+ return 0;
+}
+
+
+static lu_mem singlestep (lua_State *L) {
+ global_State *g = G(L);
+ switch (g->gcstate) {
+ case GCSpause: {
+ g->GCmemtrav = g->strt.size * sizeof(GCObject*);
+ restartcollection(g);
+ g->gcstate = GCSpropagate;
+ return g->GCmemtrav;
+ }
+ case GCSpropagate: {
+ g->GCmemtrav = 0;
+ lua_assert(g->gray);
+ propagatemark(g);
+ if (g->gray == NULL) /* no more gray objects? */
+ g->gcstate = GCSatomic; /* finish propagate phase */
+ return g->GCmemtrav; /* memory traversed in this step */
+ }
+ case GCSatomic: {
+ lu_mem work;
+ int sw;
+ propagateall(g); /* make sure gray list is empty */
+ work = atomic(L); /* work is what was traversed by 'atomic' */
+ sw = entersweep(L);
+ g->GCestimate = gettotalbytes(g); /* first estimate */;
+ return work + sw * GCSWEEPCOST;
+ }
+ case GCSswpallgc: { /* sweep "regular" objects */
+ return sweepstep(L, g, GCSswpfinobj, &g->finobj);
+ }
+ case GCSswpfinobj: { /* sweep objects with finalizers */
+ return sweepstep(L, g, GCSswptobefnz, &g->tobefnz);
+ }
+ case GCSswptobefnz: { /* sweep objects to be finalized */
+ return sweepstep(L, g, GCSswpend, NULL);
+ }
+ case GCSswpend: { /* finish sweeps */
+ makewhite(g, g->mainthread); /* sweep main thread */
+ checkSizes(L, g);
+ g->gcstate = GCScallfin;
+ return 0;
+ }
+ case GCScallfin: { /* call remaining finalizers */
+ if (g->tobefnz && g->gckind != KGC_EMERGENCY) {
+ int n = runafewfinalizers(L);
+ return (n * GCFINALIZECOST);
+ }
+ else { /* emergency mode or no more finalizers */
+ g->gcstate = GCSpause; /* finish collection */
+ return 0;
+ }
+ }
+ default: lua_assert(0); return 0;
+ }
+}
+
+
+/*
+** advances the garbage collector until it reaches a state allowed
+** by 'statemask'
+*/
+void luaC_runtilstate (lua_State *L, int statesmask) {
+ global_State *g = G(L);
+ while (!testbit(statesmask, g->gcstate))
+ singlestep(L);
+}
+
+
+/*
+** get GC debt and convert it from Kb to 'work units' (avoid zero debt
+** and overflows)
+*/
+static l_mem getdebt (global_State *g) {
+ l_mem debt = g->GCdebt;
+ int stepmul = g->gcstepmul;
+ debt = (debt / STEPMULADJ) + 1;
+ debt = (debt < MAX_LMEM / stepmul) ? debt * stepmul : MAX_LMEM;
+ return debt;
+}
+
+/*
+** performs a basic GC step when collector is running
+*/
+void luaC_step (lua_State *L) {
+ global_State *g = G(L);
+ l_mem debt = getdebt(g); /* GC deficit (be paid now) */
+ if (!g->gcrunning) { /* not running? */
+ luaE_setdebt(g, -GCSTEPSIZE * 10); /* avoid being called too often */
+ return;
+ }
+ do { /* repeat until pause or enough "credit" (negative debt) */
+ lu_mem work = singlestep(L); /* perform one single step */
+ debt -= work;
+ } while (debt > -GCSTEPSIZE && g->gcstate != GCSpause);
+ if (g->gcstate == GCSpause)
+ setpause(g); /* pause until next cycle */
+ else {
+ debt = (debt / g->gcstepmul) * STEPMULADJ; /* convert 'work units' to Kb */
+ luaE_setdebt(g, debt);
+ runafewfinalizers(L);
+ }
+}
+
+
+/*
+** Performs a full GC cycle; if 'isemergency', set a flag to avoid
+** some operations which could change the interpreter state in some
+** unexpected ways (running finalizers and shrinking some structures).
+** Before running the collection, check 'keepinvariant'; if it is true,
+** there may be some objects marked as black, so the collector has
+** to sweep all objects to turn them back to white (as white has not
+** changed, nothing will be collected).
+*/
+void luaC_fullgc (lua_State *L, int isemergency) {
+ global_State *g = G(L);
+ lua_assert(g->gckind == KGC_NORMAL);
+ if (isemergency) g->gckind = KGC_EMERGENCY; /* set flag */
+ if (keepinvariant(g)) { /* black objects? */
+ entersweep(L); /* sweep everything to turn them back to white */
+ }
+ /* finish any pending sweep phase to start a new cycle */
+ luaC_runtilstate(L, bitmask(GCSpause));
+ luaC_runtilstate(L, ~bitmask(GCSpause)); /* start new collection */
+ luaC_runtilstate(L, bitmask(GCScallfin)); /* run up to finalizers */
+ /* estimate must be correct after a full GC cycle */
+ lua_assert(g->GCestimate == gettotalbytes(g));
+ luaC_runtilstate(L, bitmask(GCSpause)); /* finish collection */
+ g->gckind = KGC_NORMAL;
+ setpause(g);
+}
+
+/* }====================================================== */
+
+
diff --git a/src/lgc.h b/src/lgc.h
new file mode 100644
index 0000000000..0eedf84204
--- /dev/null
+++ b/src/lgc.h
@@ -0,0 +1,138 @@
+/*
+** $Id: lgc.h,v 2.86 2014/10/25 11:50:46 roberto Exp $
+** Garbage Collector
+** See Copyright Notice in lua.h
+*/
+
+#ifndef lgc_h
+#define lgc_h
+
+
+#include "lobject.h"
+#include "lstate.h"
+
+/*
+** Collectable objects may have one of three colors: white, which
+** means the object is not marked; gray, which means the
+** object is marked, but its references may be not marked; and
+** black, which means that the object and all its references are marked.
+** The main invariant of the garbage collector, while marking objects,
+** is that a black object can never point to a white one. Moreover,
+** any gray object must be in a "gray list" (gray, grayagain, weak,
+** allweak, ephemeron) so that it can be visited again before finishing
+** the collection cycle. These lists have no meaning when the invariant
+** is not being enforced (e.g., sweep phase).
+*/
+
+
+
+/* how much to allocate before next GC step */
+#if !defined(GCSTEPSIZE)
+/* ~100 small strings */
+#define GCSTEPSIZE (cast_int(100 * sizeof(TString)))
+#endif
+
+
+/*
+** Possible states of the Garbage Collector
+*/
+#define GCSpropagate 0
+#define GCSatomic 1
+#define GCSswpallgc 2
+#define GCSswpfinobj 3
+#define GCSswptobefnz 4
+#define GCSswpend 5
+#define GCScallfin 6
+#define GCSpause 7
+
+
+#define issweepphase(g) \
+ (GCSswpallgc <= (g)->gcstate && (g)->gcstate <= GCSswpend)
+
+
+/*
+** macro to tell when main invariant (white objects cannot point to black
+** ones) must be kept. During a collection, the sweep
+** phase may break the invariant, as objects turned white may point to
+** still-black objects. The invariant is restored when sweep ends and
+** all objects are white again.
+*/
+
+#define keepinvariant(g) ((g)->gcstate <= GCSatomic)
+
+
+/*
+** some useful bit tricks
+*/
+#define resetbits(x,m) ((x) &= cast(lu_byte, ~(m)))
+#define setbits(x,m) ((x) |= (m))
+#define testbits(x,m) ((x) & (m))
+#define bitmask(b) (1<<(b))
+#define bit2mask(b1,b2) (bitmask(b1) | bitmask(b2))
+#define l_setbit(x,b) setbits(x, bitmask(b))
+#define resetbit(x,b) resetbits(x, bitmask(b))
+#define testbit(x,b) testbits(x, bitmask(b))
+
+
+/* Layout for bit use in 'marked' field: */
+#define WHITE0BIT 0 /* object is white (type 0) */
+#define WHITE1BIT 1 /* object is white (type 1) */
+#define BLACKBIT 2 /* object is black */
+#define FINALIZEDBIT 3 /* object has been marked for finalization */
+/* bit 7 is currently used by tests (luaL_checkmemory) */
+
+#define WHITEBITS bit2mask(WHITE0BIT, WHITE1BIT)
+
+
+#define iswhite(x) testbits((x)->marked, WHITEBITS)
+#define isblack(x) testbit((x)->marked, BLACKBIT)
+#define isgray(x) /* neither white nor black */ \
+ (!testbits((x)->marked, WHITEBITS | bitmask(BLACKBIT)))
+
+#define tofinalize(x) testbit((x)->marked, FINALIZEDBIT)
+
+#define otherwhite(g) ((g)->currentwhite ^ WHITEBITS)
+#define isdeadm(ow,m) (!(((m) ^ WHITEBITS) & (ow)))
+#define isdead(g,v) isdeadm(otherwhite(g), (v)->marked)
+
+#define changewhite(x) ((x)->marked ^= WHITEBITS)
+#define gray2black(x) l_setbit((x)->marked, BLACKBIT)
+
+#define luaC_white(g) cast(lu_byte, (g)->currentwhite & WHITEBITS)
+
+
+#define luaC_condGC(L,c) \
+ {if (G(L)->GCdebt > 0) {c;}; condchangemem(L);}
+#define luaC_checkGC(L) luaC_condGC(L, luaC_step(L);)
+
+
+#define luaC_barrier(L,p,v) { \
+ if (iscollectable(v) && isblack(p) && iswhite(gcvalue(v))) \
+ luaC_barrier_(L,obj2gco(p),gcvalue(v)); }
+
+#define luaC_barrierback(L,p,v) { \
+ if (iscollectable(v) && isblack(p) && iswhite(gcvalue(v))) \
+ luaC_barrierback_(L,p); }
+
+#define luaC_objbarrier(L,p,o) { \
+ if (isblack(p) && iswhite(o)) \
+ luaC_barrier_(L,obj2gco(p),obj2gco(o)); }
+
+#define luaC_upvalbarrier(L,uv) \
+ { if (iscollectable((uv)->v) && !upisopen(uv)) \
+ luaC_upvalbarrier_(L,uv); }
+
+LUAI_FUNC void luaC_fix (lua_State *L, GCObject *o);
+LUAI_FUNC void luaC_freeallobjects (lua_State *L);
+LUAI_FUNC void luaC_step (lua_State *L);
+LUAI_FUNC void luaC_runtilstate (lua_State *L, int statesmask);
+LUAI_FUNC void luaC_fullgc (lua_State *L, int isemergency);
+LUAI_FUNC GCObject *luaC_newobj (lua_State *L, int tt, size_t sz);
+LUAI_FUNC void luaC_barrier_ (lua_State *L, GCObject *o, GCObject *v);
+LUAI_FUNC void luaC_barrierback_ (lua_State *L, Table *o);
+LUAI_FUNC void luaC_upvalbarrier_ (lua_State *L, UpVal *uv);
+LUAI_FUNC void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt);
+LUAI_FUNC void luaC_upvdeccount (lua_State *L, UpVal *uv);
+
+
+#endif
diff --git a/src/linit.c b/src/linit.c
new file mode 100644
index 0000000000..8ce94ccb35
--- /dev/null
+++ b/src/linit.c
@@ -0,0 +1,68 @@
+/*
+** $Id: linit.c,v 1.38 2015/01/05 13:48:33 roberto Exp $
+** Initialization of libraries for lua.c and other clients
+** See Copyright Notice in lua.h
+*/
+
+
+#define linit_c
+#define LUA_LIB
+
+/*
+** If you embed Lua in your program and need to open the standard
+** libraries, call luaL_openlibs in your program. If you need a
+** different set of libraries, copy this file to your project and edit
+** it to suit your needs.
+**
+** You can also *preload* libraries, so that a later 'require' can
+** open the library, which is already linked to the application.
+** For that, do the following code:
+**
+** luaL_getsubtable(L, LUA_REGISTRYINDEX, "_PRELOAD");
+** lua_pushcfunction(L, luaopen_modname);
+** lua_setfield(L, -2, modname);
+** lua_pop(L, 1); // remove _PRELOAD table
+*/
+
+#include "lprefix.h"
+
+
+#include
+
+#include "lua.h"
+
+#include "lualib.h"
+#include "lauxlib.h"
+
+
+/*
+** these libs are loaded by lua.c and are readily available to any Lua
+** program
+*/
+static const luaL_Reg loadedlibs[] = {
+ {"_G", luaopen_base},
+ {LUA_LOADLIBNAME, luaopen_package},
+ {LUA_COLIBNAME, luaopen_coroutine},
+ {LUA_TABLIBNAME, luaopen_table},
+ {LUA_IOLIBNAME, luaopen_io},
+ {LUA_OSLIBNAME, luaopen_os},
+ {LUA_STRLIBNAME, luaopen_string},
+ {LUA_MATHLIBNAME, luaopen_math},
+ {LUA_UTF8LIBNAME, luaopen_utf8},
+ {LUA_DBLIBNAME, luaopen_debug},
+#if defined(LUA_COMPAT_BITLIB)
+ {LUA_BITLIBNAME, luaopen_bit32},
+#endif
+ {NULL, NULL}
+};
+
+
+LUALIB_API void luaL_openlibs (lua_State *L) {
+ const luaL_Reg *lib;
+ /* "require" functions from 'loadedlibs' and set results to global table */
+ for (lib = loadedlibs; lib->func; lib++) {
+ luaL_requiref(L, lib->name, lib->func, 1);
+ lua_pop(L, 1); /* remove lib */
+ }
+}
+
diff --git a/liolib.c b/src/liolib.c
similarity index 73%
rename from liolib.c
rename to src/liolib.c
index 57615e6f32..4dea39684a 100644
--- a/liolib.c
+++ b/src/liolib.c
@@ -1,5 +1,5 @@
/*
-** $Id: liolib.c $
+** $Id: liolib.c,v 2.142 2015/01/02 12:50:28 roberto Exp $
** Standard I/O (and system) library
** See Copyright Notice in lua.h
*/
@@ -21,26 +21,20 @@
#include "lauxlib.h"
#include "lualib.h"
-#include "llimits.h"
+#if !defined(l_checkmode)
+
/*
+** Check whether 'mode' matches '[rwa]%+?b?'.
** Change this macro to accept other modes for 'fopen' besides
** the standard ones.
*/
-#if !defined(l_checkmode)
-
-/* accepted extensions to 'mode' in 'fopen' */
-#if !defined(L_MODEEXT)
-#define L_MODEEXT "b"
-#endif
-
-/* Check whether 'mode' matches '[rwa]%+?[L_MODEEXT]*' */
-static int l_checkmode (const char *mode) {
- return (*mode != '\0' && strchr("rwa", *(mode++)) != NULL &&
- (*mode != '+' || ((void)(++mode), 1)) && /* skip if char is '+' */
- (strspn(mode, L_MODEEXT) == strlen(mode))); /* check extensions */
-}
+#define l_checkmode(mode) \
+ (*mode != '\0' && strchr("rwa", *(mode++)) != NULL && \
+ (*mode != '+' || ++mode) && /* skip if char is '+' */ \
+ (*mode != 'b' || ++mode) && /* skip if char is 'b' */ \
+ (*mode == '\0'))
#endif
@@ -63,17 +57,11 @@ static int l_checkmode (const char *mode) {
#define l_popen(L,c,m) (_popen(c,m))
#define l_pclose(L,file) (_pclose(file))
-#if !defined(l_checkmodep)
-/* Windows accepts "[rw][bt]?" as valid modes */
-#define l_checkmodep(m) ((m[0] == 'r' || m[0] == 'w') && \
- (m[1] == '\0' || ((m[1] == 'b' || m[1] == 't') && m[2] == '\0')))
-#endif
-
#else /* }{ */
/* ISO C definitions */
#define l_popen(L,c,m) \
- ((void)c, (void)m, \
+ ((void)((void)c, m), \
luaL_error(L, "'popen' not supported"), \
(FILE*)0)
#define l_pclose(L,file) ((void)L, (void)file, -1)
@@ -82,12 +70,6 @@ static int l_checkmode (const char *mode) {
#endif /* } */
-
-#if !defined(l_checkmodep)
-/* By default, Lua accepts only "r" or "w" as valid modes */
-#define l_checkmodep(m) ((m[0] == 'r' || m[0] == 'w') && m[1] == '\0')
-#endif
-
/* }====================================================== */
@@ -114,7 +96,7 @@ static int l_checkmode (const char *mode) {
#if !defined(l_fseek) /* { */
-#if defined(LUA_USE_POSIX) || defined(LUA_USE_OFF_T) /* { */
+#if defined(LUA_USE_POSIX) /* { */
#include
@@ -144,7 +126,6 @@ static int l_checkmode (const char *mode) {
/* }====================================================== */
-
#define IO_PREFIX "_IO_"
#define IOPREF_LEN (sizeof(IO_PREFIX)/sizeof(char) - 1)
#define IO_INPUT (IO_PREFIX "input")
@@ -164,7 +145,7 @@ static int io_type (lua_State *L) {
luaL_checkany(L, 1);
p = (LStream *)luaL_testudata(L, 1, LUA_FILEHANDLE);
if (p == NULL)
- luaL_pushfail(L); /* not a file */
+ lua_pushnil(L); /* not a file */
else if (isclosed(p))
lua_pushliteral(L, "closed file");
else
@@ -185,7 +166,7 @@ static int f_tostring (lua_State *L) {
static FILE *tofile (lua_State *L) {
LStream *p = tolstream(L);
- if (l_unlikely(isclosed(p)))
+ if (isclosed(p))
luaL_error(L, "attempt to use a closed file");
lua_assert(p->f);
return p->f;
@@ -195,10 +176,10 @@ static FILE *tofile (lua_State *L) {
/*
** When creating file handles, always creates a 'closed' file handle
** before opening the actual file; so, if there is a memory error, the
-** handle is in a consistent state.
+** file is not left opened.
*/
static LStream *newprefile (lua_State *L) {
- LStream *p = (LStream *)lua_newuserdatauv(L, sizeof(LStream), 0);
+ LStream *p = (LStream *)lua_newuserdata(L, sizeof(LStream));
p->closef = NULL; /* mark file handle as 'closed' */
luaL_setmetatable(L, LUA_FILEHANDLE);
return p;
@@ -218,16 +199,11 @@ static int aux_close (lua_State *L) {
}
-static int f_close (lua_State *L) {
- tofile(L); /* make sure argument is an open stream */
- return aux_close(L);
-}
-
-
static int io_close (lua_State *L) {
if (lua_isnone(L, 1)) /* no argument? */
- lua_getfield(L, LUA_REGISTRYINDEX, IO_OUTPUT); /* use default output */
- return f_close(L);
+ lua_getfield(L, LUA_REGISTRYINDEX, IO_OUTPUT); /* use standard output */
+ tofile(L); /* make sure argument is an open stream */
+ return aux_close(L);
}
@@ -244,8 +220,8 @@ static int f_gc (lua_State *L) {
*/
static int io_fclose (lua_State *L) {
LStream *p = tolstream(L);
- errno = 0;
- return luaL_fileresult(L, (fclose(p->f) == 0), NULL);
+ int res = fclose(p->f);
+ return luaL_fileresult(L, (res == 0), NULL);
}
@@ -260,7 +236,7 @@ static LStream *newfile (lua_State *L) {
static void opencheck (lua_State *L, const char *fname, const char *mode) {
LStream *p = newfile(L);
p->f = fopen(fname, mode);
- if (l_unlikely(p->f == NULL))
+ if (p->f == NULL)
luaL_error(L, "cannot open file '%s' (%s)", fname, strerror(errno));
}
@@ -271,7 +247,6 @@ static int io_open (lua_State *L) {
LStream *p = newfile(L);
const char *md = mode; /* to traverse/check mode */
luaL_argcheck(L, l_checkmode(md), 2, "invalid mode");
- errno = 0;
p->f = fopen(filename, mode);
return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1;
}
@@ -282,7 +257,6 @@ static int io_open (lua_State *L) {
*/
static int io_pclose (lua_State *L) {
LStream *p = tolstream(L);
- errno = 0;
return luaL_execresult(L, l_pclose(L, p->f));
}
@@ -291,8 +265,6 @@ static int io_popen (lua_State *L) {
const char *filename = luaL_checkstring(L, 1);
const char *mode = luaL_optstring(L, 2, "r");
LStream *p = newprefile(L);
- luaL_argcheck(L, l_checkmodep(mode), 2, "invalid mode");
- errno = 0;
p->f = l_popen(L, filename, mode);
p->closef = &io_pclose;
return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1;
@@ -301,7 +273,6 @@ static int io_popen (lua_State *L) {
static int io_tmpfile (lua_State *L) {
LStream *p = newfile(L);
- errno = 0;
p->f = tmpfile();
return (p->f == NULL) ? luaL_fileresult(L, 0, NULL) : 1;
}
@@ -311,8 +282,8 @@ static FILE *getiofile (lua_State *L, const char *findex) {
LStream *p;
lua_getfield(L, LUA_REGISTRYINDEX, findex);
p = (LStream *)lua_touserdata(L, -1);
- if (l_unlikely(isclosed(p)))
- luaL_error(L, "default %s file is closed", findex + IOPREF_LEN);
+ if (isclosed(p))
+ luaL_error(L, "standard %s file is closed", findex + IOPREF_LEN);
return p->f;
}
@@ -347,28 +318,11 @@ static int io_output (lua_State *L) {
static int io_readline (lua_State *L);
-/*
-** maximum number of arguments to 'f:lines'/'io.lines' (it + 3 must fit
-** in the limit for upvalues of a closure)
-*/
-#define MAXARGLINE 250
-
-/*
-** Auxiliary function to create the iteration function for 'lines'.
-** The iteration function is a closure over 'io_readline', with
-** the following upvalues:
-** 1) The file being read (first value in the stack)
-** 2) the number of arguments to read
-** 3) a boolean, true iff file has to be closed when finished ('toclose')
-** *) a variable number of format arguments (rest of the stack)
-*/
static void aux_lines (lua_State *L, int toclose) {
int n = lua_gettop(L) - 1; /* number of arguments to read */
- luaL_argcheck(L, n <= MAXARGLINE, MAXARGLINE + 2, "too many arguments");
- lua_pushvalue(L, 1); /* file */
lua_pushinteger(L, n); /* number of arguments to read */
lua_pushboolean(L, toclose); /* close/not close file when finished */
- lua_rotate(L, 2, 3); /* move the three values to their positions */
+ lua_rotate(L, 2, 2); /* move 'n' and 'toclose' to their positions */
lua_pushcclosure(L, io_readline, 3 + n);
}
@@ -380,11 +334,6 @@ static int f_lines (lua_State *L) {
}
-/*
-** Return an iteration function for 'io.lines'. If file has to be
-** closed, also returns the file itself as a second result (to be
-** closed as the state at the exit of a generic for).
-*/
static int io_lines (lua_State *L) {
int toclose;
if (lua_isnone(L, 1)) lua_pushnil(L); /* at least one argument */
@@ -400,15 +349,8 @@ static int io_lines (lua_State *L) {
lua_replace(L, 1); /* put file at index 1 */
toclose = 1; /* close it after iteration */
}
- aux_lines(L, toclose); /* push iteration function */
- if (toclose) {
- lua_pushnil(L); /* state */
- lua_pushnil(L); /* control */
- lua_pushvalue(L, 1); /* file is the to-be-closed variable (4th result) */
- return 4;
- }
- else
- return 1;
+ aux_lines(L, toclose);
+ return 1;
}
@@ -420,17 +362,14 @@ static int io_lines (lua_State *L) {
/* maximum length of a numeral */
-#if !defined (L_MAXLENNUM)
-#define L_MAXLENNUM 200
-#endif
-
+#define MAXRN 200
/* auxiliary structure used by 'read_number' */
typedef struct {
FILE *f; /* file being read */
int c; /* current character (look ahead) */
int n; /* number of elements in buffer 'buff' */
- char buff[L_MAXLENNUM + 1]; /* +1 for ending '\0' */
+ char buff[MAXRN + 1]; /* +1 for ending '\0' */
} RN;
@@ -438,12 +377,12 @@ typedef struct {
** Add current char to buffer (if not out of space) and read next one
*/
static int nextc (RN *rn) {
- if (l_unlikely(rn->n >= L_MAXLENNUM)) { /* buffer overflow? */
+ if (rn->n >= MAXRN) { /* buffer overflow? */
rn->buff[0] = '\0'; /* invalidate result */
return 0; /* fail */
}
else {
- rn->buff[rn->n++] = cast_char(rn->c); /* save current char */
+ rn->buff[rn->n++] = rn->c; /* save current char */
rn->c = l_getc(rn->f); /* read next one */
return 1;
}
@@ -451,10 +390,10 @@ static int nextc (RN *rn) {
/*
-** Accept current char if it is in 'set' (of size 2)
+** Accept current char if it is in 'set' (of size 1 or 2)
*/
static int test2 (RN *rn, const char *set) {
- if (rn->c == set[0] || rn->c == set[1])
+ if (rn->c == set[0] || (rn->c == set[1] && rn->c != '\0'))
return nextc(rn);
else return 0;
}
@@ -471,23 +410,28 @@ static int readdigits (RN *rn, int hex) {
}
+/* access to locale "radix character" (decimal point) */
+#if !defined(l_getlocaledecpoint)
+#define l_getlocaledecpoint() (localeconv()->decimal_point[0])
+#endif
+
+
/*
** Read a number: first reads a valid prefix of a numeral into a buffer.
** Then it calls 'lua_stringtonumber' to check whether the format is
-** correct and to convert it to a Lua number.
+** correct and to convert it to a Lua number
*/
static int read_number (lua_State *L, FILE *f) {
RN rn;
int count = 0;
int hex = 0;
- char decp[2];
+ char decp[2] = ".";
rn.f = f; rn.n = 0;
- decp[0] = lua_getlocaledecpoint(); /* get decimal point from locale */
- decp[1] = '.'; /* always accept a dot */
+ decp[0] = l_getlocaledecpoint(); /* get decimal point from locale */
l_lockfile(rn.f);
do { rn.c = l_getc(rn.f); } while (isspace(rn.c)); /* skip spaces */
- test2(&rn, "-+"); /* optional sign */
- if (test2(&rn, "00")) {
+ test2(&rn, "-+"); /* optional signal */
+ if (test2(&rn, "0")) {
if (test2(&rn, "xX")) hex = 1; /* numeral is hexadecimal */
else count = 1; /* count initial '0' as a valid digit */
}
@@ -495,14 +439,14 @@ static int read_number (lua_State *L, FILE *f) {
if (test2(&rn, decp)) /* decimal point? */
count += readdigits(&rn, hex); /* fractional part */
if (count > 0 && test2(&rn, (hex ? "pP" : "eE"))) { /* exponent mark? */
- test2(&rn, "-+"); /* exponent sign */
+ test2(&rn, "-+"); /* exponent signal */
readdigits(&rn, 0); /* exponent digits */
}
ungetc(rn.c, rn.f); /* unread look-ahead char */
l_unlockfile(rn.f);
rn.buff[rn.n] = '\0'; /* finish string */
- if (l_likely(lua_stringtonumber(L, rn.buff)))
- return 1; /* ok, it is a valid number */
+ if (lua_stringtonumber(L, rn.buff)) /* is this a valid number? */
+ return 1; /* ok */
else { /* invalid format */
lua_pushnil(L); /* "result" to be removed */
return 0; /* read fails */
@@ -513,26 +457,26 @@ static int read_number (lua_State *L, FILE *f) {
static int test_eof (lua_State *L, FILE *f) {
int c = getc(f);
ungetc(c, f); /* no-op when c == EOF */
- lua_pushliteral(L, "");
+ lua_pushlstring(L, NULL, 0);
return (c != EOF);
}
static int read_line (lua_State *L, FILE *f, int chop) {
luaL_Buffer b;
- int c;
+ int c = '\0';
luaL_buffinit(L, &b);
- do { /* may need to read several chunks to get whole line */
- char *buff = luaL_prepbuffer(&b); /* preallocate buffer space */
- unsigned i = 0;
+ while (c != EOF && c != '\n') { /* repeat until end of line */
+ char *buff = luaL_prepbuffer(&b); /* pre-allocate buffer */
+ int i = 0;
l_lockfile(f); /* no memory errors can happen inside the lock */
while (i < LUAL_BUFFERSIZE && (c = l_getc(f)) != EOF && c != '\n')
- buff[i++] = cast_char(c); /* read up to end of line or buffer limit */
+ buff[i++] = c;
l_unlockfile(f);
luaL_addsize(&b, i);
- } while (c != EOF && c != '\n'); /* repeat until end of line */
+ }
if (!chop && c == '\n') /* want a newline and have one? */
- luaL_addchar(&b, '\n'); /* add ending newline to result */
+ luaL_addchar(&b, c); /* add ending newline to result */
luaL_pushresult(&b); /* close buffer */
/* return ok if read something (either a newline or something else) */
return (c == '\n' || lua_rawlen(L, -1) > 0);
@@ -544,7 +488,7 @@ static void read_all (lua_State *L, FILE *f) {
luaL_Buffer b;
luaL_buffinit(L, &b);
do { /* read file in chunks of LUAL_BUFFERSIZE bytes */
- char *p = luaL_prepbuffer(&b);
+ char *p = luaL_prepbuffsize(&b, LUAL_BUFFERSIZE);
nr = fread(p, sizeof(char), LUAL_BUFFERSIZE, f);
luaL_addsize(&b, nr);
} while (nr == LUAL_BUFFERSIZE);
@@ -567,15 +511,14 @@ static int read_chars (lua_State *L, FILE *f, size_t n) {
static int g_read (lua_State *L, FILE *f, int first) {
int nargs = lua_gettop(L) - 1;
- int n, success;
+ int success;
+ int n;
clearerr(f);
- errno = 0;
if (nargs == 0) { /* no arguments? */
success = read_line(L, f, 1);
- n = first + 1; /* to return 1 result */
+ n = first+1; /* to return 1 result */
}
- else {
- /* ensure stack space for all results and for auxlib's buffer */
+ else { /* ensure stack space for all results and for auxlib's buffer */
luaL_checkstack(L, nargs+LUA_MINSTACK, "too many arguments");
success = 1;
for (n = first; nargs-- && success; n++) {
@@ -610,7 +553,7 @@ static int g_read (lua_State *L, FILE *f, int first) {
return luaL_fileresult(L, 0, NULL);
if (!success) {
lua_pop(L, 1); /* remove last result */
- luaL_pushfail(L); /* push nil instead */
+ lua_pushnil(L); /* push nil instead */
}
return n - first;
}
@@ -626,9 +569,6 @@ static int f_read (lua_State *L) {
}
-/*
-** Iteration function for 'lines'.
-*/
static int io_readline (lua_State *L) {
LStream *p = (LStream *)lua_touserdata(L, lua_upvalueindex(1));
int i;
@@ -643,14 +583,14 @@ static int io_readline (lua_State *L) {
lua_assert(n > 0); /* should return at least a nil */
if (lua_toboolean(L, -n)) /* read at least one value? */
return n; /* return them */
- else { /* first result is false: EOF or error */
+ else { /* first result is nil: EOF or error */
if (n > 1) { /* is there error information? */
/* 2nd result is error message */
return luaL_error(L, "%s", lua_tostring(L, -n + 1));
}
if (lua_toboolean(L, lua_upvalueindex(3))) { /* generator created file? */
- lua_settop(L, 0); /* clear stack */
- lua_pushvalue(L, lua_upvalueindex(1)); /* push file at index 1 */
+ lua_settop(L, 0);
+ lua_pushvalue(L, lua_upvalueindex(1));
aux_close(L); /* close it */
}
return 0;
@@ -662,28 +602,23 @@ static int io_readline (lua_State *L) {
static int g_write (lua_State *L, FILE *f, int arg) {
int nargs = lua_gettop(L) - arg;
- size_t totalbytes = 0; /* total number of bytes written */
- errno = 0;
- for (; nargs--; arg++) { /* for each argument */
- char buff[LUA_N2SBUFFSZ];
- const char *s;
- size_t numbytes; /* bytes written in one call to 'fwrite' */
- size_t len = lua_numbertocstring(L, arg, buff); /* try as a number */
- if (len > 0) { /* did conversion work (value was a number)? */
- s = buff;
- len--;
+ int status = 1;
+ for (; nargs--; arg++) {
+ if (lua_type(L, arg) == LUA_TNUMBER) {
+ /* optimization: could be done exactly as for strings */
+ int len = lua_isinteger(L, arg)
+ ? fprintf(f, LUA_INTEGER_FMT, lua_tointeger(L, arg))
+ : fprintf(f, LUA_NUMBER_FMT, lua_tonumber(L, arg));
+ status = status && (len > 0);
}
- else /* must be a string */
- s = luaL_checklstring(L, arg, &len);
- numbytes = fwrite(s, sizeof(char), len, f);
- totalbytes += numbytes;
- if (numbytes < len) { /* write error? */
- int n = luaL_fileresult(L, 0, NULL);
- lua_pushinteger(L, cast_st2S(totalbytes));
- return n + 1; /* return fail, error msg., error code, and counter */
+ else {
+ size_t l;
+ const char *s = luaL_checklstring(L, arg, &l);
+ status = status && (fwrite(s, sizeof(char), l, f) == l);
}
}
- return 1; /* no errors; file handle already on stack top */
+ if (status) return 1; /* file handle already on stack top */
+ else return luaL_fileresult(L, status, NULL);
}
@@ -708,9 +643,8 @@ static int f_seek (lua_State *L) {
l_seeknum offset = (l_seeknum)p3;
luaL_argcheck(L, (lua_Integer)offset == p3, 3,
"not an integer in proper range");
- errno = 0;
op = l_fseek(f, offset, mode[op]);
- if (l_unlikely(op))
+ if (op)
return luaL_fileresult(L, 0, NULL); /* error */
else {
lua_pushinteger(L, (lua_Integer)l_ftell(f));
@@ -725,26 +659,19 @@ static int f_setvbuf (lua_State *L) {
FILE *f = tofile(L);
int op = luaL_checkoption(L, 2, NULL, modenames);
lua_Integer sz = luaL_optinteger(L, 3, LUAL_BUFFERSIZE);
- int res;
- errno = 0;
- res = setvbuf(f, NULL, mode[op], (size_t)sz);
+ int res = setvbuf(f, NULL, mode[op], (size_t)sz);
return luaL_fileresult(L, res == 0, NULL);
}
-static int aux_flush (lua_State *L, FILE *f) {
- errno = 0;
- return luaL_fileresult(L, fflush(f) == 0, NULL);
-}
-
-static int f_flush (lua_State *L) {
- return aux_flush(L, tofile(L));
+static int io_flush (lua_State *L) {
+ return luaL_fileresult(L, fflush(getiofile(L, IO_OUTPUT)) == 0, NULL);
}
-static int io_flush (lua_State *L) {
- return aux_flush(L, getiofile(L, IO_OUTPUT));
+static int f_flush (lua_State *L) {
+ return luaL_fileresult(L, fflush(tofile(L)) == 0, NULL);
}
@@ -770,37 +697,26 @@ static const luaL_Reg iolib[] = {
/*
** methods for file handles
*/
-static const luaL_Reg meth[] = {
- {"read", f_read},
- {"write", f_write},
- {"lines", f_lines},
+static const luaL_Reg flib[] = {
+ {"close", io_close},
{"flush", f_flush},
+ {"lines", f_lines},
+ {"read", f_read},
{"seek", f_seek},
- {"close", f_close},
{"setvbuf", f_setvbuf},
- {NULL, NULL}
-};
-
-
-/*
-** metamethods for file handles
-*/
-static const luaL_Reg metameth[] = {
- {"__index", NULL}, /* placeholder */
+ {"write", f_write},
{"__gc", f_gc},
- {"__close", f_gc},
{"__tostring", f_tostring},
{NULL, NULL}
};
static void createmeta (lua_State *L) {
- luaL_newmetatable(L, LUA_FILEHANDLE); /* metatable for file handles */
- luaL_setfuncs(L, metameth, 0); /* add metamethods to new metatable */
- luaL_newlibtable(L, meth); /* create method table */
- luaL_setfuncs(L, meth, 0); /* add file methods to method table */
- lua_setfield(L, -2, "__index"); /* metatable.__index = method table */
- lua_pop(L, 1); /* pop metatable */
+ 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_setfuncs(L, flib, 0); /* add file methods to new metatable */
+ lua_pop(L, 1); /* pop new metatable */
}
@@ -810,7 +726,7 @@ static void createmeta (lua_State *L) {
static int io_noclose (lua_State *L) {
LStream *p = tolstream(L);
p->closef = &io_noclose; /* keep file opened */
- luaL_pushfail(L);
+ lua_pushnil(L);
lua_pushliteral(L, "cannot close standard file");
return 2;
}
diff --git a/llex.c b/src/llex.c
similarity index 70%
rename from llex.c
rename to src/llex.c
index 7cd9fcaf52..6e4a457ad6 100644
--- a/llex.c
+++ b/src/llex.c
@@ -1,5 +1,5 @@
/*
-** $Id: llex.c $
+** $Id: llex.c,v 2.89 2014/11/14 16:06:09 roberto Exp $
** Lexical Analyzer
** See Copyright Notice in lua.h
*/
@@ -16,7 +16,6 @@
#include "lua.h"
#include "lctype.h"
-#include "ldebug.h"
#include "ldo.h"
#include "lgc.h"
#include "llex.h"
@@ -29,14 +28,9 @@
-#define next(ls) (ls->current = zgetc(ls->z))
+#define next(ls) (ls->current = zgetc(ls->z))
-/* minimum size for string buffer */
-#if !defined(LUA_MINBUFFER)
-#define LUA_MINBUFFER 32
-#endif
-
#define currIsNewline(ls) (ls->current == '\n' || ls->current == '\r')
@@ -44,7 +38,7 @@
/* ORDER RESERVED */
static const char *const luaX_tokens [] = {
"and", "break", "do", "else", "elseif",
- "end", "false", "for", "function", "global", "goto", "if",
+ "end", "false", "for", "function", "goto", "if",
"in", "local", "nil", "not", "or", "repeat",
"return", "then", "true", "until", "while",
"//", "..", "...", "==", ">=", "<=", "~=",
@@ -62,19 +56,19 @@ static l_noret lexerror (LexState *ls, const char *msg, int token);
static void save (LexState *ls, int c) {
Mbuffer *b = ls->buff;
if (luaZ_bufflen(b) + 1 > luaZ_sizebuffer(b)) {
- size_t newsize = luaZ_sizebuffer(b); /* get old size */;
- if (newsize >= (MAX_SIZE/3 * 2)) /* larger than MAX_SIZE/1.5 ? */
+ size_t newsize;
+ if (luaZ_sizebuffer(b) >= MAX_SIZE/2)
lexerror(ls, "lexical element too long", 0);
- newsize += (newsize >> 1); /* new size is 1.5 times the old one */
+ newsize = luaZ_sizebuffer(b) * 2;
luaZ_resizebuffer(ls->L, b, newsize);
}
- b->buffer[luaZ_bufflen(b)++] = cast_char(c);
+ b->buffer[luaZ_bufflen(b)++] = cast(char, c);
}
void luaX_init (lua_State *L) {
int i;
- TString *e = luaS_newliteral(L, LUA_ENV); /* create env name */
+ TString *e = luaS_new(L, LUA_ENV); /* create env name */
luaC_fix(L, obj2gco(e)); /* never collect this name */
for (i=0; iL, "'%c'", token);
- else /* control character */
- return luaO_pushfstring(ls->L, "'<\\%d>'", token);
+ lua_assert(token == cast_uchar(token));
+ return luaO_pushfstring(ls->L, "'%c'", token);
}
else {
const char *s = luaX_tokens[token - FIRST_RESERVED];
@@ -114,7 +106,9 @@ static const char *txtToken (LexState *ls, int token) {
static l_noret lexerror (LexState *ls, const char *msg, int token) {
- msg = luaG_addinfo(ls->L, msg, ls->source, ls->linenumber);
+ char buff[LUA_IDSIZE];
+ luaO_chunkid(buff, getstr(ls->source), LUA_IDSIZE);
+ msg = luaO_pushfstring(ls->L, "%s:%d: %s", buff, ls->linenumber, msg);
if (token)
luaO_pushfstring(ls->L, "%s near %s", msg, txtToken(ls, token));
luaD_throw(ls->L, LUA_ERRSYNTAX);
@@ -127,34 +121,27 @@ l_noret luaX_syntaxerror (LexState *ls, const char *msg) {
/*
-** Anchors a string in scanner's table so that it will not be collected
-** until the end of the compilation; by that time it should be anchored
-** somewhere. It also internalizes long strings, ensuring there is only
-** one copy of each unique string.
+** creates a new string and anchors it in scanner's table so that
+** it will not be collected until the end of the compilation
+** (by that time it should be anchored somewhere)
*/
-static TString *anchorstr (LexState *ls, TString *ts) {
+TString *luaX_newstring (LexState *ls, const char *str, size_t l) {
lua_State *L = ls->L;
- TValue oldts;
- int tag = luaH_getstr(ls->h, ts, &oldts);
- if (!tagisempty(tag)) /* string already present? */
- return tsvalue(&oldts); /* use stored value */
- else { /* create a new entry */
- TValue *stv = s2v(L->top.p++); /* reserve stack space for string */
- setsvalue(L, stv, ts); /* push (anchor) the string on the stack */
- luaH_set(L, ls->h, stv, stv); /* t[string] = string */
- /* table is not a metatable, so it does not need to invalidate cache */
+ TValue *o; /* entry for 'str' */
+ TString *ts = luaS_newlstr(L, str, l); /* create new string */
+ setsvalue2s(L, L->top++, ts); /* temporarily anchor it in stack */
+ o = luaH_set(L, ls->h, L->top - 1);
+ if (ttisnil(o)) { /* not in use yet? */
+ /* boolean value does not need GC barrier;
+ table has no metatable, so it does not need to invalidate cache */
+ setbvalue(o, 1); /* t[string] = true */
luaC_checkGC(L);
- L->top.p--; /* remove string from stack */
- return ts;
}
-}
-
-
-/*
-** Creates a new string and anchors it in scanner's table.
-*/
-TString *luaX_newstring (LexState *ls, const char *str, size_t l) {
- return anchorstr(ls, luaS_newlstr(ls->L, str, l));
+ else { /* string already present */
+ ts = tsvalue(keyfromval(o)); /* re-use value previously stored */
+ }
+ L->top--; /* remove string from stack */
+ return ts;
}
@@ -168,7 +155,7 @@ static void inclinenumber (LexState *ls) {
next(ls); /* skip '\n' or '\r' */
if (currIsNewline(ls) && ls->current != old)
next(ls); /* skip '\n\r' or '\r\n' */
- if (++ls->linenumber >= INT_MAX)
+ if (++ls->linenumber >= MAX_INT)
lexerror(ls, "chunk has too many lines", 0);
}
@@ -176,6 +163,7 @@ static void inclinenumber (LexState *ls) {
void luaX_setinput (lua_State *L, LexState *ls, ZIO *z, TString *source,
int firstchar) {
ls->t.token = 0;
+ ls->decpoint = '.';
ls->L = L;
ls->current = firstchar;
ls->lookahead.token = TK_EOS; /* no look-ahead token */
@@ -184,15 +172,7 @@ void luaX_setinput (lua_State *L, LexState *ls, ZIO *z, TString *source,
ls->linenumber = 1;
ls->lastline = 1;
ls->source = source;
- /* all three strings here ("_ENV", "break", "global") were fixed,
- so they cannot be collected */
- ls->envn = luaS_newliteral(L, LUA_ENV); /* get env string */
- ls->brkn = luaS_newliteral(L, "break"); /* get "break" string */
-#if LUA_COMPAT_GLOBAL
- /* compatibility mode: "global" is not a reserved word */
- ls->glbn = luaS_newliteral(L, "global"); /* get "global" string */
- ls->glbn->extra = 0; /* mark it as not reserved */
-#endif
+ ls->envn = luaS_new(L, LUA_ENV); /* get env name */
luaZ_resizebuffer(ls->L, ls->buff, LUA_MINBUFFER); /* initialize buffer */
}
@@ -228,18 +208,46 @@ static int check_next2 (LexState *ls, const char *set) {
}
+/*
+** change all characters 'from' in buffer to 'to'
+*/
+static void buffreplace (LexState *ls, char from, char to) {
+ if (from != to) {
+ size_t n = luaZ_bufflen(ls->buff);
+ char *p = luaZ_buffer(ls->buff);
+ while (n--)
+ if (p[n] == from) p[n] = to;
+ }
+}
+
+
+#if !defined(l_getlocaledecpoint)
+#define l_getlocaledecpoint() (localeconv()->decimal_point[0])
+#endif
+
+
+#define buff2num(b,o) (luaO_str2num(luaZ_buffer(b), o) != 0)
+
+/*
+** in case of format error, try to change decimal point separator to
+** the one defined in the current locale and check again
+*/
+static void trydecpoint (LexState *ls, TValue *o) {
+ char old = ls->decpoint;
+ ls->decpoint = l_getlocaledecpoint();
+ buffreplace(ls, old, ls->decpoint); /* try new decimal separator */
+ if (!buff2num(ls->buff, o)) {
+ /* format error with correct decimal point: no more options */
+ buffreplace(ls, ls->decpoint, '.'); /* undo change (for error message) */
+ lexerror(ls, "malformed number", TK_FLT);
+ }
+}
+
+
/* LUA_NUMBER */
/*
-** This function is quite liberal in what it accepts, as 'luaO_str2num'
-** will reject ill-formed numerals. Roughly, it accepts the following
-** pattern:
-**
-** %d(%x|%.|([Ee][+-]?))* | 0[Xx](%x|%.|([Pp][+-]?))*
-**
-** The only tricky part is to accept [+-] only after a valid exponent
-** mark, to avoid reading '3-4' or '0xe+1' as a single number.
-**
-** The caller might have already read an initial dot.
+** this function is quite liberal in what it accepts, as 'luaO_str2num'
+** will reject ill-formed numerals.
*/
static int read_numeral (LexState *ls, SemInfo *seminfo) {
TValue obj;
@@ -250,17 +258,18 @@ static int read_numeral (LexState *ls, SemInfo *seminfo) {
if (first == '0' && check_next2(ls, "xX")) /* hexadecimal? */
expo = "Pp";
for (;;) {
- if (check_next2(ls, expo)) /* exponent mark? */
+ if (check_next2(ls, expo)) /* exponent part? */
check_next2(ls, "-+"); /* optional exponent sign */
- else if (lisxdigit(ls->current) || ls->current == '.') /* '%x|%.' */
+ if (lisxdigit(ls->current))
+ save_and_next(ls);
+ else if (ls->current == '.')
save_and_next(ls);
else break;
}
- if (lislalpha(ls->current)) /* is numeral touching a letter? */
- save_and_next(ls); /* force an error */
save(ls, '\0');
- if (luaO_str2num(luaZ_buffer(ls->buff), &obj) == 0) /* format error? */
- lexerror(ls, "malformed number", TK_FLT);
+ buffreplace(ls, '.', ls->decpoint); /* follow locale for decimal point */
+ if (!buff2num(ls->buff, &obj)) /* format error? */
+ trydecpoint(ls, &obj); /* try to update decimal point separator */
if (ttisinteger(&obj)) {
seminfo->i = ivalue(&obj);
return TK_INT;
@@ -274,13 +283,11 @@ static int read_numeral (LexState *ls, SemInfo *seminfo) {
/*
-** read a sequence '[=*[' or ']=*]', leaving the last bracket. If
-** sequence is well formed, return its number of '='s + 2; otherwise,
-** return 1 if it is a single bracket (no '='s and no 2nd bracket);
-** otherwise (an unfinished '[==...') return 0.
+** skip a sequence '[=*[' or ']=*]' and return its number of '='s or
+** -1 if sequence is malformed
*/
-static size_t skip_sep (LexState *ls) {
- size_t count = 0;
+static int skip_sep (LexState *ls) {
+ int count = 0;
int s = ls->current;
lua_assert(s == '[' || s == ']');
save_and_next(ls);
@@ -288,13 +295,11 @@ static size_t skip_sep (LexState *ls) {
save_and_next(ls);
count++;
}
- return (ls->current == s) ? count + 2
- : (count == 0) ? 1
- : 0;
+ return (ls->current == s) ? count : (-count) - 1;
}
-static void read_long_string (LexState *ls, SemInfo *seminfo, size_t sep) {
+static void read_long_string (LexState *ls, SemInfo *seminfo, int sep) {
int line = ls->linenumber; /* initial line (for error message) */
save_and_next(ls); /* skip 2nd '[' */
if (currIsNewline(ls)) /* string starts with a newline? */
@@ -328,8 +333,8 @@ static void read_long_string (LexState *ls, SemInfo *seminfo, size_t sep) {
}
} endloop:
if (seminfo)
- seminfo->ts = luaX_newstring(ls, luaZ_buffer(ls->buff) + sep,
- luaZ_bufflen(ls->buff) - 2 * sep);
+ seminfo->ts = luaX_newstring(ls, luaZ_buffer(ls->buff) + (2 + sep),
+ luaZ_bufflen(ls->buff) - 2*(2 + sep));
}
@@ -357,21 +362,16 @@ static int readhexaesc (LexState *ls) {
}
-/*
-** When reading a UTF-8 escape sequence, save everything to the buffer
-** for error reporting in case of errors; 'i' counts the number of
-** saved characters, so that they can be removed if case of success.
-*/
-static l_uint32 readutf8esc (LexState *ls) {
- l_uint32 r;
- int i = 4; /* number of chars to be removed: start with #"\u{X" */
+static unsigned long readutf8esc (LexState *ls) {
+ unsigned long r;
+ int i = 4; /* chars to be removed: '\', 'u', '{', and first digit */
save_and_next(ls); /* skip 'u' */
esccheck(ls, ls->current == '{', "missing '{'");
- r = cast_uint(gethexa(ls)); /* must have at least one digit */
- while (cast_void(save_and_next(ls)), lisxdigit(ls->current)) {
+ r = gethexa(ls); /* must have at least one digit */
+ while ((save_and_next(ls), lisxdigit(ls->current))) {
i++;
- esccheck(ls, r <= (0x7FFFFFFFu >> 4), "UTF-8 value too large");
r = (r << 4) + luaO_hexavalue(ls->current);
+ esccheck(ls, r <= 0x10FFFF, "UTF-8 value too large");
}
esccheck(ls, ls->current == '}', "missing '}'");
next(ls); /* skip '}' */
@@ -482,9 +482,9 @@ static int llex (LexState *ls, SemInfo *seminfo) {
/* else is a comment */
next(ls);
if (ls->current == '[') { /* long comment? */
- size_t sep = skip_sep(ls);
+ int sep = skip_sep(ls);
luaZ_resetbuffer(ls->buff); /* 'skip_sep' may dirty the buffer */
- if (sep >= 2) {
+ if (sep >= 0) {
read_long_string(ls, NULL, sep); /* skip long comment */
luaZ_resetbuffer(ls->buff); /* previous call may dirty the buff. */
break;
@@ -496,45 +496,44 @@ static int llex (LexState *ls, SemInfo *seminfo) {
break;
}
case '[': { /* long string or simply '[' */
- size_t sep = skip_sep(ls);
- if (sep >= 2) {
+ int sep = skip_sep(ls);
+ if (sep >= 0) {
read_long_string(ls, seminfo, sep);
return TK_STRING;
}
- else if (sep == 0) /* '[=...' missing second bracket? */
- lexerror(ls, "invalid long string delimiter", TK_STRING);
- return '[';
+ else if (sep == -1) return '[';
+ else lexerror(ls, "invalid long string delimiter", TK_STRING);
}
case '=': {
next(ls);
- if (check_next1(ls, '=')) return TK_EQ; /* '==' */
+ if (check_next1(ls, '=')) return TK_EQ;
else return '=';
}
case '<': {
next(ls);
- if (check_next1(ls, '=')) return TK_LE; /* '<=' */
- else if (check_next1(ls, '<')) return TK_SHL; /* '<<' */
+ if (check_next1(ls, '=')) return TK_LE;
+ else if (check_next1(ls, '<')) return TK_SHL;
else return '<';
}
case '>': {
next(ls);
- if (check_next1(ls, '=')) return TK_GE; /* '>=' */
- else if (check_next1(ls, '>')) return TK_SHR; /* '>>' */
+ if (check_next1(ls, '=')) return TK_GE;
+ else if (check_next1(ls, '>')) return TK_SHR;
else return '>';
}
case '/': {
next(ls);
- if (check_next1(ls, '/')) return TK_IDIV; /* '//' */
+ if (check_next1(ls, '/')) return TK_IDIV;
else return '/';
}
case '~': {
next(ls);
- if (check_next1(ls, '=')) return TK_NE; /* '~=' */
+ if (check_next1(ls, '=')) return TK_NE;
else return '~';
}
case ':': {
next(ls);
- if (check_next1(ls, ':')) return TK_DBCOLON; /* '::' */
+ if (check_next1(ls, ':')) return TK_DBCOLON;
else return ':';
}
case '"': case '\'': { /* short literal strings */
@@ -564,17 +563,16 @@ static int llex (LexState *ls, SemInfo *seminfo) {
do {
save_and_next(ls);
} while (lislalnum(ls->current));
- /* find or create string */
- ts = luaS_newlstr(ls->L, luaZ_buffer(ls->buff),
- luaZ_bufflen(ls->buff));
- if (isreserved(ts)) /* reserved word? */
+ ts = luaX_newstring(ls, luaZ_buffer(ls->buff),
+ luaZ_bufflen(ls->buff));
+ seminfo->ts = ts;
+ if (isreserved(ts)) /* reserved word? */
return ts->extra - 1 + FIRST_RESERVED;
else {
- seminfo->ts = anchorstr(ls, ts);
return TK_NAME;
}
}
- else { /* single-char tokens ('+', '*', '%', '{', '}', ...) */
+ else { /* single-char tokens (+ - / ...) */
int c = ls->current;
next(ls);
return c;
diff --git a/llex.h b/src/llex.h
similarity index 76%
rename from llex.h
rename to src/llex.h
index 37016e8a3f..afb40b5622 100644
--- a/llex.h
+++ b/src/llex.h
@@ -1,5 +1,5 @@
/*
-** $Id: llex.h $
+** $Id: llex.h,v 1.78 2014/10/29 15:38:24 roberto Exp $
** Lexical Analyzer
** See Copyright Notice in lua.h
*/
@@ -7,17 +7,11 @@
#ifndef llex_h
#define llex_h
-#include
-
#include "lobject.h"
#include "lzio.h"
-/*
-** Single-char tokens (terminal symbols) are represented by their own
-** numeric code. Other tokens start at the following value.
-*/
-#define FIRST_RESERVED (UCHAR_MAX + 1)
+#define FIRST_RESERVED 257
#if !defined(LUA_ENV)
@@ -33,8 +27,8 @@ enum RESERVED {
/* terminal symbols denoted by reserved words */
TK_AND = FIRST_RESERVED, TK_BREAK,
TK_DO, TK_ELSE, TK_ELSEIF, TK_END, TK_FALSE, TK_FOR, TK_FUNCTION,
- TK_GLOBAL, TK_GOTO, TK_IF, TK_IN, TK_LOCAL, TK_NIL, TK_NOT, TK_OR,
- TK_REPEAT, TK_RETURN, TK_THEN, TK_TRUE, TK_UNTIL, TK_WHILE,
+ TK_GOTO, TK_IF, TK_IN, TK_LOCAL, TK_NIL, TK_NOT, TK_OR, TK_REPEAT,
+ TK_RETURN, TK_THEN, TK_TRUE, TK_UNTIL, TK_WHILE,
/* other terminal symbols */
TK_IDIV, TK_CONCAT, TK_DOTS, TK_EQ, TK_GE, TK_LE, TK_NE,
TK_SHL, TK_SHR,
@@ -43,7 +37,7 @@ enum RESERVED {
};
/* number of reserved words */
-#define NUM_RESERVED (cast_int(TK_WHILE-FIRST_RESERVED + 1))
+#define NUM_RESERVED (cast(int, TK_WHILE-FIRST_RESERVED+1))
typedef union {
@@ -59,7 +53,7 @@ typedef struct Token {
} Token;
-/* state of the scanner plus state of the parser when shared by all
+/* state of the lexer plus state of the parser when shared by all
functions */
typedef struct LexState {
int current; /* current character (charint) */
@@ -75,8 +69,7 @@ typedef struct LexState {
struct Dyndata *dyd; /* dynamic structures used by the parser */
TString *source; /* current source name */
TString *envn; /* environment variable name */
- TString *brkn; /* "break" name (used as a label) */
- TString *glbn; /* "global" name (when not a reserved word) */
+ char decpoint; /* locale decimal point */
} LexState;
diff --git a/src/llimits.h b/src/llimits.h
new file mode 100644
index 0000000000..8f71a6ffb9
--- /dev/null
+++ b/src/llimits.h
@@ -0,0 +1,242 @@
+/*
+** $Id: llimits.h,v 1.125 2014/12/19 13:30:23 roberto Exp $
+** Limits, basic types, and some other 'installation-dependent' definitions
+** See Copyright Notice in lua.h
+*/
+
+#ifndef llimits_h
+#define llimits_h
+
+
+#include
+#include
+
+
+#include "lua.h"
+
+/*
+** 'lu_mem' and 'l_mem' are unsigned/signed integers big enough to count
+** the total memory used by Lua (in bytes). Usually, 'size_t' and
+** 'ptrdiff_t' should work, but we use 'long' for 16-bit machines.
+*/
+#if defined(LUAI_MEM) /* { external definitions? */
+typedef LUAI_UMEM lu_mem;
+typedef LUAI_MEM l_mem;
+#elif LUAI_BITSINT >= 32 /* }{ */
+typedef size_t lu_mem;
+typedef ptrdiff_t l_mem;
+#else /* 16-bit ints */ /* }{ */
+typedef unsigned long lu_mem;
+typedef long l_mem;
+#endif /* } */
+
+
+/* chars used as small naturals (so that 'char' is reserved for characters) */
+typedef unsigned char lu_byte;
+
+
+/* maximum value for size_t */
+#define MAX_SIZET ((size_t)(~(size_t)0))
+
+/* maximum size visible for Lua (must be representable in a lua_Integer */
+#define MAX_SIZE (sizeof(size_t) < sizeof(lua_Integer) ? MAX_SIZET \
+ : (size_t)(LUA_MAXINTEGER))
+
+
+#define MAX_LUMEM ((lu_mem)(~(lu_mem)0))
+
+#define MAX_LMEM ((l_mem)(MAX_LUMEM >> 1))
+
+
+#define MAX_INT INT_MAX /* maximum value of an int */
+
+
+/*
+** conversion of pointer to integer:
+** this is for hashing only; there is no problem if the integer
+** cannot hold the whole pointer value
+*/
+#define point2int(p) ((unsigned int)((size_t)(p) & UINT_MAX))
+
+
+
+/* type to ensure maximum alignment */
+#if defined(LUAI_USER_ALIGNMENT_T)
+typedef LUAI_USER_ALIGNMENT_T L_Umaxalign;
+#else
+typedef union { double u; void *s; lua_Integer i; long l; } L_Umaxalign;
+#endif
+
+
+
+/* types of 'usual argument conversions' for lua_Number and lua_Integer */
+typedef LUAI_UACNUMBER l_uacNumber;
+typedef LUAI_UACINT l_uacInt;
+
+
+/* internal assertions for in-house debugging */
+#if defined(lua_assert)
+#define check_exp(c,e) (lua_assert(c), (e))
+/* to avoid problems with conditions too long */
+#define lua_longassert(c) { if (!(c)) lua_assert(0); }
+#else
+#define lua_assert(c) ((void)0)
+#define check_exp(c,e) (e)
+#define lua_longassert(c) ((void)0)
+#endif
+
+/*
+** assertion for checking API calls
+*/
+#if defined(LUA_USE_APICHECK)
+#include
+#define luai_apicheck(e) assert(e)
+#else
+#define luai_apicheck(e) lua_assert(e)
+#endif
+
+
+#define api_check(e,msg) luai_apicheck((e) && msg)
+
+
+#if !defined(UNUSED)
+#define UNUSED(x) ((void)(x)) /* to avoid warnings */
+#endif
+
+
+#define cast(t, exp) ((t)(exp))
+
+#define cast_void(i) cast(void, (i))
+#define cast_byte(i) cast(lu_byte, (i))
+#define cast_num(i) cast(lua_Number, (i))
+#define cast_int(i) cast(int, (i))
+#define cast_uchar(i) cast(unsigned char, (i))
+
+
+/* cast a signed lua_Integer to lua_Unsigned */
+#if !defined(l_castS2U)
+#define l_castS2U(i) ((lua_Unsigned)(i))
+#endif
+
+/*
+** cast a lua_Unsigned to a signed lua_Integer; this cast is
+** not strict ISO C, but two-complement architectures should
+** work fine.
+*/
+#if !defined(l_castU2S)
+#define l_castU2S(i) ((lua_Integer)(i))
+#endif
+
+
+/*
+** non-return type
+*/
+#if defined(__GNUC__)
+#define l_noret void __attribute__((noreturn))
+#elif defined(_MSC_VER) && _MSC_VER >= 1200
+#define l_noret void __declspec(noreturn)
+#else
+#define l_noret void
+#endif
+
+
+
+/*
+** maximum depth for nested C calls and syntactical nested non-terminals
+** in a program. (Value must fit in an unsigned short int.)
+*/
+#if !defined(LUAI_MAXCCALLS)
+#define LUAI_MAXCCALLS 200
+#endif
+
+/*
+** maximum number of upvalues in a closure (both C and Lua). (Value
+** must fit in an unsigned char.)
+*/
+#define MAXUPVAL UCHAR_MAX
+
+
+/*
+** type for virtual-machine instructions;
+** must be an unsigned with (at least) 4 bytes (see details in lopcodes.h)
+*/
+#if LUAI_BITSINT >= 32
+typedef unsigned int Instruction;
+#else
+typedef unsigned long Instruction;
+#endif
+
+
+
+
+/* minimum size for the string table (must be power of 2) */
+#if !defined(MINSTRTABSIZE)
+#define MINSTRTABSIZE 64 /* minimum size for "predefined" strings */
+#endif
+
+
+/* minimum size for string buffer */
+#if !defined(LUA_MINBUFFER)
+#define LUA_MINBUFFER 32
+#endif
+
+
+#if !defined(lua_lock)
+#define lua_lock(L) ((void) 0)
+#define lua_unlock(L) ((void) 0)
+#endif
+
+#if !defined(luai_threadyield)
+#define luai_threadyield(L) {lua_unlock(L); lua_lock(L);}
+#endif
+
+
+/*
+** these macros allow user-specific actions on threads when you defined
+** LUAI_EXTRASPACE and need to do something extra when a thread is
+** created/deleted/resumed/yielded.
+*/
+#if !defined(luai_userstateopen)
+#define luai_userstateopen(L) ((void)L)
+#endif
+
+#if !defined(luai_userstateclose)
+#define luai_userstateclose(L) ((void)L)
+#endif
+
+#if !defined(luai_userstatethread)
+#define luai_userstatethread(L,L1) ((void)L)
+#endif
+
+#if !defined(luai_userstatefree)
+#define luai_userstatefree(L,L1) ((void)L)
+#endif
+
+#if !defined(luai_userstateresume)
+#define luai_userstateresume(L,n) ((void)L)
+#endif
+
+#if !defined(luai_userstateyield)
+#define luai_userstateyield(L,n) ((void)L)
+#endif
+
+
+
+/*
+** macro to control inclusion of some hard tests on stack reallocation
+*/
+#if !defined(HARDSTACKTESTS)
+#define condmovestack(L) ((void)0)
+#else
+/* realloc stack keeping its size */
+#define condmovestack(L) luaD_reallocstack((L), (L)->stacksize)
+#endif
+
+#if !defined(HARDMEMTESTS)
+#define condchangemem(L) condmovestack(L)
+#else
+#define condchangemem(L) \
+ ((void)(!(G(L)->gcrunning) || (luaC_fullgc(L, 0), 1)))
+#endif
+
+#endif
diff --git a/src/lmathlib.c b/src/lmathlib.c
new file mode 100644
index 0000000000..002c508bc4
--- /dev/null
+++ b/src/lmathlib.c
@@ -0,0 +1,404 @@
+/*
+** $Id: lmathlib.c,v 1.114 2014/12/27 20:32:26 roberto Exp $
+** Standard mathematical library
+** See Copyright Notice in lua.h
+*/
+
+#define lmathlib_c
+#define LUA_LIB
+
+#include "lprefix.h"
+
+
+#include
+#include
+
+#include "lua.h"
+
+#include "lauxlib.h"
+#include "lualib.h"
+
+
+#undef PI
+#define PI (l_mathop(3.141592653589793238462643383279502884))
+
+
+#if !defined(l_rand) /* { */
+#if defined(LUA_USE_POSIX)
+#define l_rand() random()
+#define l_srand(x) srandom(x)
+#define L_RANDMAX 2147483647 /* (2^31 - 1), following POSIX */
+#else
+#define l_rand() rand()
+#define l_srand(x) srand(x)
+#define L_RANDMAX RAND_MAX
+#endif
+#endif /* } */
+
+
+static int math_abs (lua_State *L) {
+ if (lua_isinteger(L, 1)) {
+ lua_Integer n = lua_tointeger(L, 1);
+ if (n < 0) n = (lua_Integer)(0u - n);
+ lua_pushinteger(L, n);
+ }
+ else
+ lua_pushnumber(L, l_mathop(fabs)(luaL_checknumber(L, 1)));
+ return 1;
+}
+
+static int math_sin (lua_State *L) {
+ lua_pushnumber(L, l_mathop(sin)(luaL_checknumber(L, 1)));
+ return 1;
+}
+
+static int math_cos (lua_State *L) {
+ lua_pushnumber(L, l_mathop(cos)(luaL_checknumber(L, 1)));
+ return 1;
+}
+
+static int math_tan (lua_State *L) {
+ lua_pushnumber(L, l_mathop(tan)(luaL_checknumber(L, 1)));
+ return 1;
+}
+
+static int math_asin (lua_State *L) {
+ lua_pushnumber(L, l_mathop(asin)(luaL_checknumber(L, 1)));
+ return 1;
+}
+
+static int math_acos (lua_State *L) {
+ lua_pushnumber(L, l_mathop(acos)(luaL_checknumber(L, 1)));
+ return 1;
+}
+
+static int math_atan (lua_State *L) {
+ lua_Number y = luaL_checknumber(L, 1);
+ lua_Number x = luaL_optnumber(L, 2, 1);
+ lua_pushnumber(L, l_mathop(atan2)(y, x));
+ return 1;
+}
+
+
+static int math_toint (lua_State *L) {
+ int valid;
+ lua_Integer n = lua_tointegerx(L, 1, &valid);
+ if (valid)
+ lua_pushinteger(L, n);
+ else {
+ luaL_checkany(L, 1);
+ lua_pushnil(L); /* value is not convertible to integer */
+ }
+ return 1;
+}
+
+
+static void pushnumint (lua_State *L, lua_Number d) {
+ lua_Integer n;
+ if (lua_numbertointeger(d, &n)) /* does 'd' fit in an integer? */
+ lua_pushinteger(L, n); /* result is integer */
+ else
+ lua_pushnumber(L, d); /* result is float */
+}
+
+
+static int math_floor (lua_State *L) {
+ if (lua_isinteger(L, 1))
+ lua_settop(L, 1); /* integer is its own floor */
+ else {
+ lua_Number d = l_mathop(floor)(luaL_checknumber(L, 1));
+ pushnumint(L, d);
+ }
+ return 1;
+}
+
+
+static int math_ceil (lua_State *L) {
+ if (lua_isinteger(L, 1))
+ lua_settop(L, 1); /* integer is its own ceil */
+ else {
+ lua_Number d = l_mathop(ceil)(luaL_checknumber(L, 1));
+ pushnumint(L, d);
+ }
+ return 1;
+}
+
+
+static int math_fmod (lua_State *L) {
+ if (lua_isinteger(L, 1) && lua_isinteger(L, 2)) {
+ lua_Integer d = lua_tointeger(L, 2);
+ if ((lua_Unsigned)d + 1u <= 1u) { /* special cases: -1 or 0 */
+ luaL_argcheck(L, d != 0, 2, "zero");
+ lua_pushinteger(L, 0); /* avoid overflow with 0x80000... / -1 */
+ }
+ else
+ lua_pushinteger(L, lua_tointeger(L, 1) % d);
+ }
+ else
+ lua_pushnumber(L, l_mathop(fmod)(luaL_checknumber(L, 1),
+ luaL_checknumber(L, 2)));
+ return 1;
+}
+
+
+/*
+** next function does not use 'modf', avoiding problems with 'double*'
+** (which is not compatible with 'float*') when lua_Number is not
+** 'double'.
+*/
+static int math_modf (lua_State *L) {
+ if (lua_isinteger(L ,1)) {
+ lua_settop(L, 1); /* number is its own integer part */
+ lua_pushnumber(L, 0); /* no fractional part */
+ }
+ else {
+ lua_Number n = luaL_checknumber(L, 1);
+ /* integer part (rounds toward zero) */
+ lua_Number ip = (n < 0) ? l_mathop(ceil)(n) : l_mathop(floor)(n);
+ pushnumint(L, ip);
+ /* fractional part (test needed for inf/-inf) */
+ lua_pushnumber(L, (n == ip) ? l_mathop(0.0) : (n - ip));
+ }
+ return 2;
+}
+
+
+static int math_sqrt (lua_State *L) {
+ lua_pushnumber(L, l_mathop(sqrt)(luaL_checknumber(L, 1)));
+ return 1;
+}
+
+
+static int math_ult (lua_State *L) {
+ lua_Integer a = luaL_checkinteger(L, 1);
+ lua_Integer b = luaL_checkinteger(L, 2);
+ lua_pushboolean(L, (lua_Unsigned)a < (lua_Unsigned)b);
+ return 1;
+}
+
+static int math_log (lua_State *L) {
+ lua_Number x = luaL_checknumber(L, 1);
+ lua_Number res;
+ if (lua_isnoneornil(L, 2))
+ res = l_mathop(log)(x);
+ else {
+ lua_Number base = luaL_checknumber(L, 2);
+ if (base == 10.0) res = l_mathop(log10)(x);
+ else res = l_mathop(log)(x)/l_mathop(log)(base);
+ }
+ lua_pushnumber(L, res);
+ return 1;
+}
+
+static int math_exp (lua_State *L) {
+ lua_pushnumber(L, l_mathop(exp)(luaL_checknumber(L, 1)));
+ return 1;
+}
+
+static int math_deg (lua_State *L) {
+ lua_pushnumber(L, luaL_checknumber(L, 1) * (l_mathop(180.0) / PI));
+ return 1;
+}
+
+static int math_rad (lua_State *L) {
+ lua_pushnumber(L, luaL_checknumber(L, 1) * (PI / l_mathop(180.0)));
+ return 1;
+}
+
+
+static int math_min (lua_State *L) {
+ int n = lua_gettop(L); /* number of arguments */
+ int imin = 1; /* index of current minimum value */
+ int i;
+ luaL_argcheck(L, n >= 1, 1, "value expected");
+ for (i = 2; i <= n; i++) {
+ if (lua_compare(L, i, imin, LUA_OPLT))
+ imin = i;
+ }
+ lua_pushvalue(L, imin);
+ return 1;
+}
+
+
+static int math_max (lua_State *L) {
+ int n = lua_gettop(L); /* number of arguments */
+ int imax = 1; /* index of current maximum value */
+ int i;
+ luaL_argcheck(L, n >= 1, 1, "value expected");
+ for (i = 2; i <= n; i++) {
+ if (lua_compare(L, imax, i, LUA_OPLT))
+ imax = i;
+ }
+ lua_pushvalue(L, imax);
+ return 1;
+}
+
+/*
+** This function uses 'double' (instead of 'lua_Number') to ensure that
+** all bits from 'l_rand' can be represented, and that 'RANDMAX + 1.0'
+** will keep full precision (ensuring that 'r' is always less than 1.0.)
+*/
+static int math_random (lua_State *L) {
+ lua_Integer low, up;
+ double r = (double)l_rand() * (1.0 / ((double)L_RANDMAX + 1.0));
+ switch (lua_gettop(L)) { /* check number of arguments */
+ case 0: { /* no arguments */
+ lua_pushnumber(L, (lua_Number)r); /* Number between 0 and 1 */
+ return 1;
+ }
+ case 1: { /* only upper limit */
+ low = 1;
+ up = luaL_checkinteger(L, 1);
+ break;
+ }
+ case 2: { /* lower and upper limits */
+ low = luaL_checkinteger(L, 1);
+ up = luaL_checkinteger(L, 2);
+ break;
+ }
+ default: return luaL_error(L, "wrong number of arguments");
+ }
+ /* random integer in the interval [low, up] */
+ luaL_argcheck(L, low <= up, 1, "interval is empty");
+ luaL_argcheck(L, low >= 0 || up <= LUA_MAXINTEGER + low, 1,
+ "interval too large");
+ r *= (double)(up - low) + 1.0;
+ lua_pushinteger(L, (lua_Integer)r + low);
+ return 1;
+}
+
+
+static int math_randomseed (lua_State *L) {
+ l_srand((unsigned int)(lua_Integer)luaL_checknumber(L, 1));
+ (void)rand(); /* discard first value to avoid undesirable correlations */
+ return 0;
+}
+
+
+static int math_type (lua_State *L) {
+ if (lua_type(L, 1) == LUA_TNUMBER) {
+ if (lua_isinteger(L, 1))
+ lua_pushliteral(L, "integer");
+ else
+ lua_pushliteral(L, "float");
+ }
+ else {
+ luaL_checkany(L, 1);
+ lua_pushnil(L);
+ }
+ return 1;
+}
+
+
+/*
+** {==================================================================
+** Deprecated functions (for compatibility only)
+** ===================================================================
+*/
+#if defined(LUA_COMPAT_MATHLIB)
+
+static int math_cosh (lua_State *L) {
+ lua_pushnumber(L, l_mathop(cosh)(luaL_checknumber(L, 1)));
+ return 1;
+}
+
+static int math_sinh (lua_State *L) {
+ lua_pushnumber(L, l_mathop(sinh)(luaL_checknumber(L, 1)));
+ return 1;
+}
+
+static int math_tanh (lua_State *L) {
+ lua_pushnumber(L, l_mathop(tanh)(luaL_checknumber(L, 1)));
+ return 1;
+}
+
+static int math_pow (lua_State *L) {
+ lua_Number x = luaL_checknumber(L, 1);
+ lua_Number y = luaL_checknumber(L, 2);
+ lua_pushnumber(L, l_mathop(pow)(x, y));
+ return 1;
+}
+
+static int math_frexp (lua_State *L) {
+ int e;
+ lua_pushnumber(L, l_mathop(frexp)(luaL_checknumber(L, 1), &e));
+ lua_pushinteger(L, e);
+ return 2;
+}
+
+static int math_ldexp (lua_State *L) {
+ lua_Number x = luaL_checknumber(L, 1);
+ int ep = (int)luaL_checkinteger(L, 2);
+ lua_pushnumber(L, l_mathop(ldexp)(x, ep));
+ return 1;
+}
+
+static int math_log10 (lua_State *L) {
+ lua_pushnumber(L, l_mathop(log10)(luaL_checknumber(L, 1)));
+ return 1;
+}
+
+#endif
+/* }================================================================== */
+
+
+
+static const luaL_Reg mathlib[] = {
+ {"abs", math_abs},
+ {"acos", math_acos},
+ {"asin", math_asin},
+ {"atan", math_atan},
+ {"ceil", math_ceil},
+ {"cos", math_cos},
+ {"deg", math_deg},
+ {"exp", math_exp},
+ {"tointeger", math_toint},
+ {"floor", math_floor},
+ {"fmod", math_fmod},
+ {"ult", math_ult},
+ {"log", math_log},
+ {"max", math_max},
+ {"min", math_min},
+ {"modf", math_modf},
+ {"rad", math_rad},
+ {"random", math_random},
+ {"randomseed", math_randomseed},
+ {"sin", math_sin},
+ {"sqrt", math_sqrt},
+ {"tan", math_tan},
+ {"type", math_type},
+#if defined(LUA_COMPAT_MATHLIB)
+ {"atan2", math_atan},
+ {"cosh", math_cosh},
+ {"sinh", math_sinh},
+ {"tanh", math_tanh},
+ {"pow", math_pow},
+ {"frexp", math_frexp},
+ {"ldexp", math_ldexp},
+ {"log10", math_log10},
+#endif
+ /* placeholders */
+ {"pi", NULL},
+ {"huge", NULL},
+ {"maxinteger", NULL},
+ {"mininteger", NULL},
+ {NULL, NULL}
+};
+
+
+/*
+** Open math library
+*/
+LUAMOD_API int luaopen_math (lua_State *L) {
+ luaL_newlib(L, mathlib);
+ lua_pushnumber(L, PI);
+ lua_setfield(L, -2, "pi");
+ lua_pushnumber(L, (lua_Number)HUGE_VAL);
+ lua_setfield(L, -2, "huge");
+ lua_pushinteger(L, LUA_MAXINTEGER);
+ lua_setfield(L, -2, "maxinteger");
+ lua_pushinteger(L, LUA_MININTEGER);
+ lua_setfield(L, -2, "mininteger");
+ return 1;
+}
+
diff --git a/src/lmem.c b/src/lmem.c
new file mode 100644
index 0000000000..4feaf036c7
--- /dev/null
+++ b/src/lmem.c
@@ -0,0 +1,99 @@
+/*
+** $Id: lmem.c,v 1.89 2014/11/02 19:33:33 roberto Exp $
+** Interface to Memory Manager
+** See Copyright Notice in lua.h
+*/
+
+#define lmem_c
+#define LUA_CORE
+
+#include "lprefix.h"
+
+
+#include
+
+#include "lua.h"
+
+#include "ldebug.h"
+#include "ldo.h"
+#include "lgc.h"
+#include "lmem.h"
+#include "lobject.h"
+#include "lstate.h"
+
+
+
+/*
+** About the realloc function:
+** void * frealloc (void *ud, void *ptr, size_t osize, size_t nsize);
+** ('osize' is the old size, 'nsize' is the new size)
+**
+** * frealloc(ud, NULL, x, s) creates a new block of size 's' (no
+** matter 'x').
+**
+** * frealloc(ud, p, x, 0) frees the block 'p'
+** (in this specific case, frealloc must return NULL);
+** particularly, frealloc(ud, NULL, 0, 0) does nothing
+** (which is equivalent to free(NULL) in ISO C)
+**
+** frealloc returns NULL if it cannot create or reallocate the area
+** (any reallocation to an equal or smaller size cannot fail!)
+*/
+
+
+
+#define MINSIZEARRAY 4
+
+
+void *luaM_growaux_ (lua_State *L, void *block, int *size, size_t size_elems,
+ int limit, const char *what) {
+ void *newblock;
+ int newsize;
+ if (*size >= limit/2) { /* cannot double it? */
+ if (*size >= limit) /* cannot grow even a little? */
+ luaG_runerror(L, "too many %s (limit is %d)", what, limit);
+ newsize = limit; /* still have at least one free place */
+ }
+ else {
+ newsize = (*size)*2;
+ if (newsize < MINSIZEARRAY)
+ newsize = MINSIZEARRAY; /* minimum size */
+ }
+ newblock = luaM_reallocv(L, block, *size, newsize, size_elems);
+ *size = newsize; /* update only when everything else is OK */
+ return newblock;
+}
+
+
+l_noret luaM_toobig (lua_State *L) {
+ luaG_runerror(L, "memory allocation error: block too big");
+}
+
+
+
+/*
+** generic allocation routine.
+*/
+void *luaM_realloc_ (lua_State *L, void *block, size_t osize, size_t nsize) {
+ void *newblock;
+ global_State *g = G(L);
+ size_t realosize = (block) ? osize : 0;
+ lua_assert((realosize == 0) == (block == NULL));
+#if defined(HARDMEMTESTS)
+ if (nsize > realosize && g->gcrunning)
+ luaC_fullgc(L, 1); /* force a GC whenever possible */
+#endif
+ newblock = (*g->frealloc)(g->ud, block, osize, nsize);
+ if (newblock == NULL && nsize > 0) {
+ api_check( nsize > realosize,
+ "realloc cannot fail when shrinking a block");
+ luaC_fullgc(L, 1); /* try to free some memory... */
+ newblock = (*g->frealloc)(g->ud, block, osize, nsize); /* try again */
+ if (newblock == NULL)
+ luaD_throw(L, LUA_ERRMEM);
+ }
+ lua_assert((nsize == 0) == (newblock == NULL));
+ g->GCdebt = (g->GCdebt + nsize) - realosize;
+ return newblock;
+}
+
diff --git a/src/lmem.h b/src/lmem.h
new file mode 100644
index 0000000000..30f484895e
--- /dev/null
+++ b/src/lmem.h
@@ -0,0 +1,69 @@
+/*
+** $Id: lmem.h,v 1.43 2014/12/19 17:26:14 roberto Exp $
+** Interface to Memory Manager
+** See Copyright Notice in lua.h
+*/
+
+#ifndef lmem_h
+#define lmem_h
+
+
+#include
+
+#include "llimits.h"
+#include "lua.h"
+
+
+/*
+** This macro reallocs a vector 'b' from 'on' to 'n' elements, where
+** each element has size 'e'. In case of arithmetic overflow of the
+** product 'n'*'e', it raises an error (calling 'luaM_toobig'). Because
+** 'e' is always constant, it avoids the runtime division MAX_SIZET/(e).
+**
+** (The macro is somewhat complex to avoid warnings: The 'sizeof'
+** comparison avoids a runtime comparison when overflow cannot occur.
+** The compiler should be able to optimize the real test by itself, but
+** when it does it, it may give a warning about "comparison is always
+** false due to limited range of data type"; the +1 tricks the compiler,
+** avoiding this warning but also this optimization.)
+*/
+#define luaM_reallocv(L,b,on,n,e) \
+ (((sizeof(n) >= sizeof(size_t) && cast(size_t, (n)) + 1 > MAX_SIZET/(e)) \
+ ? luaM_toobig(L) : cast_void(0)) , \
+ luaM_realloc_(L, (b), (on)*(e), (n)*(e)))
+
+/*
+** Arrays of chars do not need any test
+*/
+#define luaM_reallocvchar(L,b,on,n) \
+ cast(char *, luaM_realloc_(L, (b), (on)*sizeof(char), (n)*sizeof(char)))
+
+#define luaM_freemem(L, b, s) luaM_realloc_(L, (b), (s), 0)
+#define luaM_free(L, b) luaM_realloc_(L, (b), sizeof(*(b)), 0)
+#define luaM_freearray(L, b, n) luaM_realloc_(L, (b), (n)*sizeof(*(b)), 0)
+
+#define luaM_malloc(L,s) luaM_realloc_(L, NULL, 0, (s))
+#define luaM_new(L,t) cast(t *, luaM_malloc(L, sizeof(t)))
+#define luaM_newvector(L,n,t) \
+ cast(t *, luaM_reallocv(L, NULL, 0, n, sizeof(t)))
+
+#define luaM_newobject(L,tag,s) luaM_realloc_(L, NULL, tag, (s))
+
+#define luaM_growvector(L,v,nelems,size,t,limit,e) \
+ if ((nelems)+1 > (size)) \
+ ((v)=cast(t *, luaM_growaux_(L,v,&(size),sizeof(t),limit,e)))
+
+#define luaM_reallocvector(L, v,oldn,n,t) \
+ ((v)=cast(t *, luaM_reallocv(L, v, oldn, n, sizeof(t))))
+
+LUAI_FUNC l_noret luaM_toobig (lua_State *L);
+
+/* not to be called directly */
+LUAI_FUNC void *luaM_realloc_ (lua_State *L, void *block, size_t oldsize,
+ size_t size);
+LUAI_FUNC void *luaM_growaux_ (lua_State *L, void *block, int *size,
+ size_t size_elem, int limit,
+ const char *what);
+
+#endif
+
diff --git a/loadlib.c b/src/loadlib.c
similarity index 60%
rename from loadlib.c
rename to src/loadlib.c
index 8d2e68e261..7f8d990298 100644
--- a/loadlib.c
+++ b/src/loadlib.c
@@ -1,5 +1,5 @@
/*
-** $Id: loadlib.c $
+** $Id: loadlib.c,v 1.124 2015/01/05 13:51:39 roberto Exp $
** Dynamic library loader for Lua
** See Copyright Notice in lua.h
**
@@ -14,7 +14,6 @@
#include "lprefix.h"
-#include
#include
#include
@@ -22,7 +21,46 @@
#include "lauxlib.h"
#include "lualib.h"
-#include "llimits.h"
+
+
+/*
+** LUA_PATH_VAR and LUA_CPATH_VAR are the names of the environment
+** variables that Lua check to set its paths.
+*/
+#if !defined(LUA_PATH_VAR)
+#define LUA_PATH_VAR "LUA_PATH"
+#endif
+
+#if !defined(LUA_CPATH_VAR)
+#define LUA_CPATH_VAR "LUA_CPATH"
+#endif
+
+#define LUA_PATHSUFFIX "_" LUA_VERSION_MAJOR "_" LUA_VERSION_MINOR
+
+#define LUA_PATHVARVERSION LUA_PATH_VAR LUA_PATHSUFFIX
+#define LUA_CPATHVARVERSION LUA_CPATH_VAR LUA_PATHSUFFIX
+
+/*
+** LUA_PATH_SEP is the character that separates templates in a path.
+** LUA_PATH_MARK is the string that marks the substitution points in a
+** template.
+** LUA_EXEC_DIR in a Windows path is replaced by the executable's
+** directory.
+** LUA_IGMARK is a mark to ignore all before it when building the
+** luaopen_ function name.
+*/
+#if !defined (LUA_PATH_SEP)
+#define LUA_PATH_SEP ";"
+#endif
+#if !defined (LUA_PATH_MARK)
+#define LUA_PATH_MARK "?"
+#endif
+#if !defined (LUA_EXEC_DIR)
+#define LUA_EXEC_DIR "!"
+#endif
+#if !defined (LUA_IGMARK)
+#define LUA_IGMARK "-"
+#endif
/*
@@ -48,19 +86,14 @@
/*
-** key for table in the registry that keeps handles
+** unique key for table in the registry that keeps handles
** for all loaded C libraries
*/
-static const char *const CLIBS = "_CLIBS";
+static const int CLIBS = 0;
#define LIB_FAIL "open"
-
-#define setprogdir(L) ((void)0)
-
-
-/* cast void* to a Lua function */
-#define cast_Lfunc(p) cast(lua_CFunction, cast_func(p))
+#define setprogdir(L) ((void)0)
/*
@@ -93,13 +126,26 @@ static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym);
#if defined(LUA_USE_DLOPEN) /* { */
/*
** {========================================================================
-** This is an implementation of loadlib based on the dlfcn interface,
-** which is available in all POSIX systems.
+** This is an implementation of loadlib based on the dlfcn interface.
+** The dlfcn interface is available in Linux, SunOS, Solaris, IRIX, FreeBSD,
+** NetBSD, AIX 4.2, HPUX 11, and probably most other Unix flavors, at least
+** as an emulation layer on top of native functions.
** =========================================================================
*/
#include
+/*
+** Macro to covert pointer to void* to pointer to function. This cast
+** is undefined according to ISO C, but POSIX assumes that it must work.
+** (The '__extension__' in gnu compilers is only to avoid warnings.)
+*/
+#if defined(__GNUC__)
+#define cast_func(p) (__extension__ (lua_CFunction)(p))
+#else
+#define cast_func(p) ((lua_CFunction)(p))
+#endif
+
static void lsys_unloadlib (void *lib) {
dlclose(lib);
@@ -108,16 +154,14 @@ static void lsys_unloadlib (void *lib) {
static void *lsys_load (lua_State *L, const char *path, int seeglb) {
void *lib = dlopen(path, RTLD_NOW | (seeglb ? RTLD_GLOBAL : RTLD_LOCAL));
- if (l_unlikely(lib == NULL))
- lua_pushstring(L, dlerror());
+ if (lib == NULL) lua_pushstring(L, dlerror());
return lib;
}
static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) {
- lua_CFunction f = cast_Lfunc(dlsym(lib, sym));
- if (l_unlikely(f == NULL))
- lua_pushstring(L, dlerror());
+ lua_CFunction f = cast_func(dlsym(lib, sym));
+ if (f == NULL) lua_pushstring(L, dlerror());
return f;
}
@@ -134,6 +178,7 @@ static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) {
#include
+#undef setprogdir
/*
** optional flags for LoadLibraryEx
@@ -143,30 +188,21 @@ static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) {
#endif
-#undef setprogdir
-
-
-/*
-** Replace in the path (on the top of the stack) any occurrence
-** of LUA_EXEC_DIR with the executable's path.
-*/
static void setprogdir (lua_State *L) {
char buff[MAX_PATH + 1];
char *lb;
DWORD nsize = sizeof(buff)/sizeof(char);
- DWORD n = GetModuleFileNameA(NULL, buff, nsize); /* get exec. name */
+ DWORD n = GetModuleFileNameA(NULL, buff, nsize);
if (n == 0 || n == nsize || (lb = strrchr(buff, '\\')) == NULL)
luaL_error(L, "unable to get ModuleFileName");
else {
- *lb = '\0'; /* cut name on the last '\\' to get the path */
+ *lb = '\0';
luaL_gsub(L, lua_tostring(L, -1), LUA_EXEC_DIR, buff);
lua_remove(L, -2); /* remove original string */
}
}
-
-
static void pusherror (lua_State *L) {
int error = GetLastError();
char buffer[128];
@@ -191,7 +227,7 @@ static void *lsys_load (lua_State *L, const char *path, int seeglb) {
static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) {
- lua_CFunction f = cast_Lfunc(GetProcAddress((HMODULE)lib, sym));
+ lua_CFunction f = (lua_CFunction)GetProcAddress((HMODULE)lib, sym);
if (f == NULL) pusherror(L);
return f;
}
@@ -235,93 +271,12 @@ static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) {
#endif /* } */
-/*
-** {==================================================================
-** Set Paths
-** ===================================================================
-*/
-
-/*
-** LUA_PATH_VAR and LUA_CPATH_VAR are the names of the environment
-** variables that Lua check to set its paths.
-*/
-#if !defined(LUA_PATH_VAR)
-#define LUA_PATH_VAR "LUA_PATH"
-#endif
-
-#if !defined(LUA_CPATH_VAR)
-#define LUA_CPATH_VAR "LUA_CPATH"
-#endif
-
-
-
-/*
-** return registry.LUA_NOENV as a boolean
-*/
-static int noenv (lua_State *L) {
- int b;
- lua_getfield(L, LUA_REGISTRYINDEX, "LUA_NOENV");
- b = lua_toboolean(L, -1);
- lua_pop(L, 1); /* remove value */
- return b;
-}
-
-
-/*
-** Set a path. (If using the default path, assume it is a string
-** literal in C and create it as an external string.)
-*/
-static void setpath (lua_State *L, const char *fieldname,
- const char *envname,
- const char *dft) {
- const char *dftmark;
- const char *nver = lua_pushfstring(L, "%s%s", envname, LUA_VERSUFFIX);
- const char *path = getenv(nver); /* try versioned name */
- if (path == NULL) /* no versioned environment variable? */
- path = getenv(envname); /* try unversioned name */
- if (path == NULL || noenv(L)) /* no environment variable? */
- lua_pushexternalstring(L, dft, strlen(dft), NULL, NULL); /* use default */
- else if ((dftmark = strstr(path, LUA_PATH_SEP LUA_PATH_SEP)) == NULL)
- lua_pushstring(L, path); /* nothing to change */
- else { /* path contains a ";;": insert default path in its place */
- size_t len = strlen(path);
- luaL_Buffer b;
- luaL_buffinit(L, &b);
- if (path < dftmark) { /* is there a prefix before ';;'? */
- luaL_addlstring(&b, path, ct_diff2sz(dftmark - path)); /* add it */
- luaL_addchar(&b, *LUA_PATH_SEP);
- }
- luaL_addstring(&b, dft); /* add default */
- if (dftmark < path + len - 2) { /* is there a suffix after ';;'? */
- luaL_addchar(&b, *LUA_PATH_SEP);
- luaL_addlstring(&b, dftmark + 2, ct_diff2sz((path + len - 2) - dftmark));
- }
- luaL_pushresult(&b);
- }
- setprogdir(L);
- lua_setfield(L, -3, fieldname); /* package[fieldname] = path value */
- lua_pop(L, 1); /* pop versioned variable name ('nver') */
-}
-
-/* }================================================================== */
-
-
-/*
-** External strings created by DLLs may need the DLL code to be
-** deallocated. This implies that a DLL can only be unloaded after all
-** its strings were deallocated. To ensure that, we create a 'library
-** string' to represent each DLL, and when this string is deallocated
-** it closes its corresponding DLL.
-** (The string itself is irrelevant; its userdata is the DLL pointer.)
-*/
-
-
/*
** return registry.CLIBS[path]
*/
static void *checkclib (lua_State *L, const char *path) {
void *plib;
- lua_getfield(L, LUA_REGISTRYINDEX, CLIBS);
+ lua_rawgetp(L, LUA_REGISTRYINDEX, &CLIBS);
lua_getfield(L, -1, path);
plib = lua_touserdata(L, -1); /* plib = CLIBS[path] */
lua_pop(L, 2); /* pop CLIBS table and 'plib' */
@@ -330,41 +285,34 @@ static void *checkclib (lua_State *L, const char *path) {
/*
-** Deallocate function for library strings.
-** Unload the DLL associated with the string being deallocated.
+** registry.CLIBS[path] = plib -- for queries
+** registry.CLIBS[#CLIBS + 1] = plib -- also keep a list of all libraries
*/
-static void *freelib (void *ud, void *ptr, size_t osize, size_t nsize) {
- /* string itself is irrelevant and static */
- (void)ptr; (void)osize; (void)nsize;
- lsys_unloadlib(ud); /* unload library represented by the string */
- return NULL;
+static void addtoclib (lua_State *L, const char *path, void *plib) {
+ lua_rawgetp(L, LUA_REGISTRYINDEX, &CLIBS);
+ lua_pushlightuserdata(L, plib);
+ lua_pushvalue(L, -1);
+ lua_setfield(L, -3, path); /* CLIBS[path] = plib */
+ lua_rawseti(L, -2, luaL_len(L, -2) + 1); /* CLIBS[#CLIBS + 1] = plib */
+ lua_pop(L, 1); /* pop CLIBS table */
}
/*
-** Create a library string that, when deallocated, will unload 'plib'
+** __gc tag method for CLIBS table: calls 'lsys_unloadlib' for all lib
+** handles in list CLIBS
*/
-static void createlibstr (lua_State *L, void *plib) {
- /* common content for all library strings */
- static const char dummy[] = "01234567890";
- lua_pushexternalstring(L, dummy, sizeof(dummy) - 1, freelib, plib);
+static int gctm (lua_State *L) {
+ lua_Integer n = luaL_len(L, 1);
+ for (; n >= 1; n--) { /* for each handle, in reverse order */
+ lua_rawgeti(L, 1, n); /* get handle CLIBS[n] */
+ lsys_unloadlib(lua_touserdata(L, -1));
+ lua_pop(L, 1); /* pop handle */
+ }
+ return 0;
}
-/*
-** registry.CLIBS[path] = plib -- for queries.
-** Also create a reference to strlib, so that the library string will
-** only be collected when registry.CLIBS is collected.
-*/
-static void addtoclib (lua_State *L, const char *path, void *plib) {
- lua_getfield(L, LUA_REGISTRYINDEX, CLIBS);
- lua_pushlightuserdata(L, plib);
- lua_setfield(L, -2, path); /* CLIBS[path] = plib */
- createlibstr(L, plib);
- luaL_ref(L, -2); /* keep library string in CLIBS */
- lua_pop(L, 1); /* pop CLIBS table */
-}
-
/* error codes for 'lookforfunc' */
#define ERRLIB 1
@@ -378,8 +326,8 @@ static void addtoclib (lua_State *L, const char *path, void *plib) {
** Then, if 'sym' is '*', return true (as library has been loaded).
** Otherwise, look for symbol 'sym' in the library and push a
** C function with that symbol.
-** Return 0 with 'true' or a function in the stack; in case of
-** errors, return an error code with an error message in the stack.
+** Return 0 and 'true' or a function in the stack; in case of
+** errors, return an error code and an error message in the stack.
*/
static int lookforfunc (lua_State *L, const char *path, const char *sym) {
void *reg = checkclib(L, path); /* check loaded C libraries */
@@ -406,13 +354,13 @@ static int ll_loadlib (lua_State *L) {
const char *path = luaL_checkstring(L, 1);
const char *init = luaL_checkstring(L, 2);
int stat = lookforfunc(L, path, init);
- if (l_likely(stat == 0)) /* no errors? */
+ if (stat == 0) /* no errors? */
return 1; /* return the loaded function */
else { /* error; error message is on stack top */
- luaL_pushfail(L);
+ lua_pushnil(L);
lua_insert(L, -2);
lua_pushstring(L, (stat == ERRLIB) ? LIB_FAIL : "init");
- return 3; /* return fail, error message, and where */
+ return 3; /* return nil, error message, and where */
}
}
@@ -433,42 +381,14 @@ static int readable (const char *filename) {
}
-/*
-** Get the next name in '*path' = 'name1;name2;name3;...', changing
-** the ending ';' to '\0' to create a zero-terminated string. Return
-** NULL when list ends.
-*/
-static const char *getnextfilename (char **path, char *end) {
- char *sep;
- char *name = *path;
- if (name == end)
- return NULL; /* no more names */
- else if (*name == '\0') { /* from previous iteration? */
- *name = *LUA_PATH_SEP; /* restore separator */
- name++; /* skip it */
- }
- sep = strchr(name, *LUA_PATH_SEP); /* find next separator */
- if (sep == NULL) /* separator not found? */
- sep = end; /* name goes until the end */
- *sep = '\0'; /* finish file name */
- *path = sep; /* will start next search from here */
- return name;
-}
-
-
-/*
-** Given a path such as ";blabla.so;blublu.so", pushes the string
-**
-** no file 'blabla.so'
-** no file 'blublu.so'
-*/
-static void pusherrornotfound (lua_State *L, const char *path) {
- luaL_Buffer b;
- luaL_buffinit(L, &b);
- luaL_addstring(&b, "no file '");
- luaL_addgsub(&b, path, LUA_PATH_SEP, "'\n\tno file '");
- luaL_addstring(&b, "'");
- luaL_pushresult(&b);
+static const char *pushnexttemplate (lua_State *L, const char *path) {
+ const char *l;
+ while (*path == *LUA_PATH_SEP) path++; /* skip separators */
+ if (*path == '\0') return NULL; /* no more templates */
+ l = strchr(path, *LUA_PATH_SEP); /* find next separator */
+ if (l == NULL) l = path + strlen(path);
+ lua_pushlstring(L, path, l - path); /* template */
+ return l;
}
@@ -476,25 +396,21 @@ static const char *searchpath (lua_State *L, const char *name,
const char *path,
const char *sep,
const char *dirsep) {
- luaL_Buffer buff;
- char *pathname; /* path with name inserted */
- char *endpathname; /* its end */
- const char *filename;
- /* separator is non-empty and appears in 'name'? */
- if (*sep != '\0' && strchr(name, *sep) != NULL)
+ luaL_Buffer msg; /* to build error message */
+ luaL_buffinit(L, &msg);
+ if (*sep != '\0') /* non-empty separator? */
name = luaL_gsub(L, name, sep, dirsep); /* replace it by 'dirsep' */
- luaL_buffinit(L, &buff);
- /* add path to the buffer, replacing marks ('?') with the file name */
- luaL_addgsub(&buff, path, LUA_PATH_MARK, name);
- luaL_addchar(&buff, '\0');
- pathname = luaL_buffaddr(&buff); /* writable list of file names */
- endpathname = pathname + luaL_bufflen(&buff) - 1;
- while ((filename = getnextfilename(&pathname, endpathname)) != NULL) {
+ while ((path = pushnexttemplate(L, path)) != NULL) {
+ const char *filename = luaL_gsub(L, lua_tostring(L, -1),
+ LUA_PATH_MARK, name);
+ lua_remove(L, -2); /* remove path template */
if (readable(filename)) /* does file exist and is readable? */
- return lua_pushstring(L, filename); /* save and return name */
+ return filename; /* return that file name */
+ lua_pushfstring(L, "\n\tno file '%s'", filename);
+ lua_remove(L, -2); /* remove file name */
+ luaL_addvalue(&msg); /* concatenate error msg. entry */
}
- luaL_pushresult(&buff); /* push path to create error message */
- pusherrornotfound(L, lua_tostring(L, -1)); /* create error message */
+ luaL_pushresult(&msg); /* create error message */
return NULL; /* not found */
}
@@ -506,9 +422,9 @@ static int ll_searchpath (lua_State *L) {
luaL_optstring(L, 4, LUA_DIRSEP));
if (f != NULL) return 1;
else { /* error message is on top of the stack */
- luaL_pushfail(L);
+ lua_pushnil(L);
lua_insert(L, -2);
- return 2; /* return fail + error message */
+ return 2; /* return nil + error message */
}
}
@@ -519,14 +435,14 @@ static const char *findfile (lua_State *L, const char *name,
const char *path;
lua_getfield(L, lua_upvalueindex(1), pname);
path = lua_tostring(L, -1);
- if (l_unlikely(path == NULL))
+ if (path == NULL)
luaL_error(L, "'package.%s' must be a string", pname);
return searchpath(L, name, path, ".", dirsep);
}
static int checkload (lua_State *L, int stat, const char *filename) {
- if (l_likely(stat)) { /* module loaded successfully? */
+ if (stat) { /* module loaded successfully? */
lua_pushstring(L, filename); /* will be 2nd argument to module */
return 2; /* return open function and file name */
}
@@ -560,7 +476,7 @@ static int loadfunc (lua_State *L, const char *filename, const char *modname) {
mark = strchr(modname, *LUA_IGMARK);
if (mark) {
int stat;
- openfunc = lua_pushlstring(L, modname, ct_diff2sz(mark - modname));
+ openfunc = lua_pushlstring(L, modname, mark - modname);
openfunc = lua_pushfstring(L, LUA_POF"%s", openfunc);
stat = lookforfunc(L, filename, openfunc);
if (stat != ERRFUNC) return stat;
@@ -585,14 +501,14 @@ static int searcher_Croot (lua_State *L) {
const char *p = strchr(name, '.');
int stat;
if (p == NULL) return 0; /* is root */
- lua_pushlstring(L, name, ct_diff2sz(p - name));
+ lua_pushlstring(L, name, p - name);
filename = findfile(L, lua_tostring(L, -1), "cpath", LUA_CSUBSEP);
if (filename == NULL) return 1; /* root not found */
if ((stat = loadfunc(L, filename, name)) != 0) {
if (stat != ERRFUNC)
return checkload(L, 0, filename); /* real error */
else { /* open function not found */
- lua_pushfstring(L, "no module '%s' in file '%s'", name, filename);
+ lua_pushfstring(L, "\n\tno module '%s' in file '%s'", name, filename);
return 1;
}
}
@@ -603,32 +519,24 @@ static int searcher_Croot (lua_State *L) {
static int searcher_preload (lua_State *L) {
const char *name = luaL_checkstring(L, 1);
- lua_getfield(L, LUA_REGISTRYINDEX, LUA_PRELOAD_TABLE);
- if (lua_getfield(L, -1, name) == LUA_TNIL) { /* not found? */
- lua_pushfstring(L, "no field package.preload['%s']", name);
- return 1;
- }
- else {
- lua_pushliteral(L, ":preload:");
- return 2;
- }
+ lua_getfield(L, LUA_REGISTRYINDEX, "_PRELOAD");
+ if (lua_getfield(L, -1, name) == LUA_TNIL) /* not found? */
+ lua_pushfstring(L, "\n\tno field package.preload['%s']", name);
+ return 1;
}
static void findloader (lua_State *L, const char *name) {
int i;
luaL_Buffer msg; /* to build error message */
+ luaL_buffinit(L, &msg);
/* push 'package.searchers' to index 3 in the stack */
- if (l_unlikely(lua_getfield(L, lua_upvalueindex(1), "searchers")
- != LUA_TTABLE))
+ if (lua_getfield(L, lua_upvalueindex(1), "searchers") != LUA_TTABLE)
luaL_error(L, "'package.searchers' must be a table");
- luaL_buffinit(L, &msg);
- luaL_addstring(&msg, "\n\t"); /* error-message prefix for first message */
/* iterate over available searchers to find a loader */
for (i = 1; ; i++) {
- if (l_unlikely(lua_rawgeti(L, 3, i) == LUA_TNIL)) { /* no more searchers? */
+ if (lua_rawgeti(L, 3, i) == LUA_TNIL) { /* no more searchers? */
lua_pop(L, 1); /* remove nil */
- luaL_buffsub(&msg, 2); /* remove last prefix */
luaL_pushresult(&msg); /* create error message */
luaL_error(L, "module '%s' not found:%s", name, lua_tostring(L, -1));
}
@@ -639,9 +547,8 @@ static void findloader (lua_State *L, const char *name) {
else if (lua_isstring(L, -2)) { /* searcher returned error message? */
lua_pop(L, 1); /* remove extra return */
luaL_addvalue(&msg); /* concatenate error message */
- luaL_addstring(&msg, "\n\t"); /* prefix for next message */
}
- else /* no error message */
+ else
lua_pop(L, 2); /* remove both returns */
}
}
@@ -649,41 +556,156 @@ static void findloader (lua_State *L, const char *name) {
static int ll_require (lua_State *L) {
const char *name = luaL_checkstring(L, 1);
- lua_settop(L, 1); /* LOADED table will be at index 2 */
- lua_getfield(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE);
- lua_getfield(L, 2, name); /* LOADED[name] */
+ lua_settop(L, 1); /* _LOADED table will be at index 2 */
+ lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
+ lua_getfield(L, 2, name); /* _LOADED[name] */
if (lua_toboolean(L, -1)) /* is it there? */
return 1; /* package is already loaded */
/* else must load package */
lua_pop(L, 1); /* remove 'getfield' result */
findloader(L, name);
- lua_rotate(L, -2, 1); /* function <-> loader data */
- lua_pushvalue(L, 1); /* name is 1st argument to module loader */
- lua_pushvalue(L, -3); /* loader data is 2nd argument */
- /* stack: ...; loader data; loader function; mod. name; loader data */
+ lua_pushstring(L, name); /* pass name as argument to module loader */
+ lua_insert(L, -2); /* name is 1st argument (before search data) */
lua_call(L, 2, 1); /* run loader to load module */
- /* stack: ...; loader data; result from loader */
if (!lua_isnil(L, -1)) /* non-nil return? */
- lua_setfield(L, 2, name); /* LOADED[name] = returned value */
- else
- lua_pop(L, 1); /* pop nil */
+ lua_setfield(L, 2, name); /* _LOADED[name] = returned value */
if (lua_getfield(L, 2, name) == LUA_TNIL) { /* module set no value? */
lua_pushboolean(L, 1); /* use true as result */
- lua_copy(L, -1, -2); /* replace loader result */
- lua_setfield(L, 2, name); /* LOADED[name] = true */
+ lua_pushvalue(L, -1); /* extra copy to be returned */
+ lua_setfield(L, 2, name); /* _LOADED[name] = true */
}
- lua_rotate(L, -2, 1); /* loader data <-> module result */
- return 2; /* return module result and loader data */
+ return 1;
}
/* }====================================================== */
+/*
+** {======================================================
+** 'module' function
+** =======================================================
+*/
+#if defined(LUA_COMPAT_MODULE)
+
+/*
+** changes the environment variable of calling function
+*/
+static void set_env (lua_State *L) {
+ lua_Debug ar;
+ if (lua_getstack(L, 1, &ar) == 0 ||
+ lua_getinfo(L, "f", &ar) == 0 || /* get calling function */
+ lua_iscfunction(L, -1))
+ luaL_error(L, "'module' not called from a Lua function");
+ lua_pushvalue(L, -2); /* copy new environment table to top */
+ lua_setupvalue(L, -2, 1);
+ lua_pop(L, 1); /* remove function */
+}
+
+
+static void dooptions (lua_State *L, int n) {
+ int i;
+ for (i = 2; i <= n; i++) {
+ if (lua_isfunction(L, i)) { /* avoid 'calling' extra info. */
+ 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);
+ int lastarg = lua_gettop(L); /* last parameter */
+ luaL_pushmodule(L, modname, 1); /* get/create module table */
+ /* check whether table already has a _NAME field */
+ if (lua_getfield(L, -1, "_NAME") != LUA_TNIL)
+ lua_pop(L, 1); /* table is an initialized module */
+ else { /* no; initialize it */
+ lua_pop(L, 1);
+ modinit(L, modname);
+ }
+ lua_pushvalue(L, -1);
+ set_env(L);
+ dooptions(L, lastarg);
+ return 1;
+}
+
+
+static int ll_seeall (lua_State *L) {
+ luaL_checktype(L, 1, LUA_TTABLE);
+ if (!lua_getmetatable(L, 1)) {
+ lua_createtable(L, 0, 1); /* create new metatable */
+ lua_pushvalue(L, -1);
+ lua_setmetatable(L, 1);
+ }
+ lua_pushglobaltable(L);
+ lua_setfield(L, -2, "__index"); /* mt.__index = _G */
+ return 0;
+}
+
+#endif
+/* }====================================================== */
+
+
+
+/* auxiliary mark (for internal use) */
+#define AUXMARK "\1"
+
+
+/*
+** return registry.LUA_NOENV as a boolean
+*/
+static int noenv (lua_State *L) {
+ int b;
+ lua_getfield(L, LUA_REGISTRYINDEX, "LUA_NOENV");
+ b = lua_toboolean(L, -1);
+ lua_pop(L, 1); /* remove value */
+ return b;
+}
+
+
+static void setpath (lua_State *L, const char *fieldname, const char *envname1,
+ const char *envname2, const char *def) {
+ const char *path = getenv(envname1);
+ if (path == NULL) /* no environment variable? */
+ path = getenv(envname2); /* try alternative name */
+ if (path == NULL || noenv(L)) /* 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_PATH_SEP LUA_PATH_SEP,
+ LUA_PATH_SEP AUXMARK LUA_PATH_SEP);
+ 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},
{"searchpath", ll_searchpath},
+#if defined(LUA_COMPAT_MODULE)
+ {"seeall", ll_seeall},
+#endif
/* placeholders */
{"preload", NULL},
{"cpath", NULL},
@@ -695,49 +717,65 @@ static const luaL_Reg pk_funcs[] = {
static const luaL_Reg ll_funcs[] = {
+#if defined(LUA_COMPAT_MODULE)
+ {"module", ll_module},
+#endif
{"require", ll_require},
{NULL, NULL}
};
static void createsearcherstable (lua_State *L) {
- static const lua_CFunction searchers[] = {
- searcher_preload,
- searcher_Lua,
- searcher_C,
- searcher_Croot,
- NULL
- };
+ static const lua_CFunction searchers[] =
+ {searcher_preload, searcher_Lua, searcher_C, searcher_Croot, NULL};
int i;
/* create 'searchers' table */
lua_createtable(L, sizeof(searchers)/sizeof(searchers[0]) - 1, 0);
- /* fill it with predefined searchers */
+ /* fill it with pre-defined searchers */
for (i=0; searchers[i] != NULL; i++) {
lua_pushvalue(L, -2); /* set 'package' as upvalue for all searchers */
lua_pushcclosure(L, searchers[i], 1);
lua_rawseti(L, -2, i+1);
}
+#if defined(LUA_COMPAT_LOADERS)
+ lua_pushvalue(L, -1); /* make a copy of 'searchers' table */
+ lua_setfield(L, -3, "loaders"); /* put it in field 'loaders' */
+#endif
lua_setfield(L, -2, "searchers"); /* put it in field 'searchers' */
}
+/*
+** create table CLIBS to keep track of loaded C libraries,
+** setting a finalizer to close all libraries when closing state.
+*/
+static void createclibstable (lua_State *L) {
+ lua_newtable(L); /* create CLIBS table */
+ lua_createtable(L, 0, 1); /* create metatable for CLIBS */
+ lua_pushcfunction(L, gctm);
+ lua_setfield(L, -2, "__gc"); /* set finalizer for CLIBS table */
+ lua_setmetatable(L, -2);
+ lua_rawsetp(L, LUA_REGISTRYINDEX, &CLIBS); /* set CLIBS table in registry */
+}
+
+
LUAMOD_API int luaopen_package (lua_State *L) {
- luaL_getsubtable(L, LUA_REGISTRYINDEX, CLIBS); /* create CLIBS table */
- lua_pop(L, 1); /* will not use it now */
+ createclibstable(L);
luaL_newlib(L, pk_funcs); /* create 'package' table */
createsearcherstable(L);
- /* set paths */
- setpath(L, "path", LUA_PATH_VAR, LUA_PATH_DEFAULT);
- setpath(L, "cpath", LUA_CPATH_VAR, LUA_CPATH_DEFAULT);
+ /* set field 'path' */
+ setpath(L, "path", LUA_PATHVARVERSION, LUA_PATH_VAR, LUA_PATH_DEFAULT);
+ /* set field 'cpath' */
+ setpath(L, "cpath", LUA_CPATHVARVERSION, LUA_CPATH_VAR, LUA_CPATH_DEFAULT);
/* store config information */
lua_pushliteral(L, LUA_DIRSEP "\n" LUA_PATH_SEP "\n" LUA_PATH_MARK "\n"
LUA_EXEC_DIR "\n" LUA_IGMARK "\n");
lua_setfield(L, -2, "config");
/* set field 'loaded' */
- luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE);
+ luaL_getsubtable(L, LUA_REGISTRYINDEX, "_LOADED");
lua_setfield(L, -2, "loaded");
/* set field 'preload' */
- luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_PRELOAD_TABLE);
+ luaL_getsubtable(L, LUA_REGISTRYINDEX, "_PRELOAD");
lua_setfield(L, -2, "preload");
lua_pushglobaltable(L);
lua_pushvalue(L, -2); /* set 'package' as upvalue for next lib */
diff --git a/src/lobject.c b/src/lobject.c
new file mode 100644
index 0000000000..6a24aff95d
--- /dev/null
+++ b/src/lobject.c
@@ -0,0 +1,470 @@
+/*
+** $Id: lobject.c,v 2.101 2014/12/26 14:43:45 roberto Exp $
+** Some generic functions over Lua objects
+** See Copyright Notice in lua.h
+*/
+
+#define lobject_c
+#define LUA_CORE
+
+#include "lprefix.h"
+
+
+#include
+#include
+#include
+#include
+
+#include "lua.h"
+
+#include "lctype.h"
+#include "ldebug.h"
+#include "ldo.h"
+#include "lmem.h"
+#include "lobject.h"
+#include "lstate.h"
+#include "lstring.h"
+#include "lvm.h"
+
+
+
+LUAI_DDEF const TValue luaO_nilobject_ = {NILCONSTANT};
+
+
+/*
+** converts an integer to a "floating point byte", represented as
+** (eeeeexxx), where the real value is (1xxx) * 2^(eeeee - 1) if
+** eeeee != 0 and (xxx) otherwise.
+*/
+int luaO_int2fb (unsigned int x) {
+ int e = 0; /* exponent */
+ if (x < 8) return x;
+ while (x >= 0x10) {
+ x = (x+1) >> 1;
+ e++;
+ }
+ return ((e+1) << 3) | (cast_int(x) - 8);
+}
+
+
+/* converts back */
+int luaO_fb2int (int x) {
+ int e = (x >> 3) & 0x1f;
+ if (e == 0) return x;
+ else return ((x & 7) + 8) << (e - 1);
+}
+
+
+int luaO_ceillog2 (unsigned int x) {
+ static const lu_byte log_2[256] = {
+ 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
+ 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
+ 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
+ 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
+ 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
+ 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
+ 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
+ 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8
+ };
+ int l = 0;
+ x--;
+ while (x >= 256) { l += 8; x >>= 8; }
+ return l + log_2[x];
+}
+
+
+static lua_Integer intarith (lua_State *L, int op, lua_Integer v1,
+ lua_Integer v2) {
+ switch (op) {
+ case LUA_OPADD: return intop(+, v1, v2);
+ case LUA_OPSUB:return intop(-, v1, v2);
+ case LUA_OPMUL:return intop(*, v1, v2);
+ case LUA_OPMOD: return luaV_mod(L, v1, v2);
+ case LUA_OPIDIV: return luaV_div(L, v1, v2);
+ case LUA_OPBAND: return intop(&, v1, v2);
+ case LUA_OPBOR: return intop(|, v1, v2);
+ case LUA_OPBXOR: return intop(^, v1, v2);
+ case LUA_OPSHL: return luaV_shiftl(v1, v2);
+ case LUA_OPSHR: return luaV_shiftl(v1, -v2);
+ case LUA_OPUNM: return intop(-, 0, v1);
+ case LUA_OPBNOT: return intop(^, ~l_castS2U(0), v1);
+ default: lua_assert(0); return 0;
+ }
+}
+
+
+static lua_Number numarith (lua_State *L, int op, lua_Number v1,
+ lua_Number v2) {
+ switch (op) {
+ case LUA_OPADD: return luai_numadd(L, v1, v2);
+ case LUA_OPSUB: return luai_numsub(L, v1, v2);
+ case LUA_OPMUL: return luai_nummul(L, v1, v2);
+ case LUA_OPDIV: return luai_numdiv(L, v1, v2);
+ case LUA_OPPOW: return luai_numpow(L, v1, v2);
+ case LUA_OPIDIV: return luai_numidiv(L, v1, v2);
+ case LUA_OPUNM: return luai_numunm(L, v1);
+ case LUA_OPMOD: {
+ lua_Number m;
+ luai_nummod(L, v1, v2, m);
+ return m;
+ }
+ default: lua_assert(0); return 0;
+ }
+}
+
+
+void luaO_arith (lua_State *L, int op, const TValue *p1, const TValue *p2,
+ TValue *res) {
+ switch (op) {
+ case LUA_OPBAND: case LUA_OPBOR: case LUA_OPBXOR:
+ case LUA_OPSHL: case LUA_OPSHR:
+ case LUA_OPBNOT: { /* operate only on integers */
+ lua_Integer i1; lua_Integer i2;
+ if (tointeger(p1, &i1) && tointeger(p2, &i2)) {
+ setivalue(res, intarith(L, op, i1, i2));
+ return;
+ }
+ else break; /* go to the end */
+ }
+ case LUA_OPDIV: case LUA_OPPOW: { /* operate only on floats */
+ lua_Number n1; lua_Number n2;
+ if (tonumber(p1, &n1) && tonumber(p2, &n2)) {
+ setfltvalue(res, numarith(L, op, n1, n2));
+ return;
+ }
+ else break; /* go to the end */
+ }
+ default: { /* other operations */
+ lua_Number n1; lua_Number n2;
+ if (ttisinteger(p1) && ttisinteger(p2)) {
+ setivalue(res, intarith(L, op, ivalue(p1), ivalue(p2)));
+ return;
+ }
+ else if (tonumber(p1, &n1) && tonumber(p2, &n2)) {
+ setfltvalue(res, numarith(L, op, n1, n2));
+ return;
+ }
+ else break; /* go to the end */
+ }
+ }
+ /* could not perform raw operation; try metamethod */
+ lua_assert(L != NULL); /* should not fail when folding (compile time) */
+ luaT_trybinTM(L, p1, p2, res, cast(TMS, op - LUA_OPADD + TM_ADD));
+}
+
+
+int luaO_hexavalue (int c) {
+ if (lisdigit(c)) return c - '0';
+ else return ltolower(c) - 'a' + 10;
+}
+
+
+static int isneg (const char **s) {
+ if (**s == '-') { (*s)++; return 1; }
+ else if (**s == '+') (*s)++;
+ return 0;
+}
+
+
+
+/*
+** {==================================================================
+** Lua's implementation for 'lua_strx2number'
+** ===================================================================
+*/
+#if !defined(lua_strx2number)
+
+#include
+
+/* maximum number of significant digits to read (to avoid overflows
+ even with single floats) */
+#define MAXSIGDIG 30
+
+/*
+** convert an hexadecimal numeric string to a number, following
+** C99 specification for 'strtod'
+*/
+static lua_Number lua_strx2number (const char *s, char **endptr) {
+ lua_Number r = 0.0; /* result (accumulator) */
+ int sigdig = 0; /* number of significant digits */
+ int nosigdig = 0; /* number of non-significant digits */
+ int e = 0; /* exponent correction */
+ int neg; /* 1 if number is negative */
+ int dot = 0; /* true after seen a dot */
+ *endptr = cast(char *, s); /* nothing is valid yet */
+ while (lisspace(cast_uchar(*s))) s++; /* skip initial spaces */
+ neg = isneg(&s); /* check signal */
+ if (!(*s == '0' && (*(s + 1) == 'x' || *(s + 1) == 'X'))) /* check '0x' */
+ return 0.0; /* invalid format (no '0x') */
+ for (s += 2; ; s++) { /* skip '0x' and read numeral */
+ if (*s == '.') {
+ if (dot) break; /* second dot? stop loop */
+ else dot = 1;
+ }
+ else if (lisxdigit(cast_uchar(*s))) {
+ if (sigdig == 0 && *s == '0') /* non-significant digit (zero)? */
+ nosigdig++;
+ else if (++sigdig <= MAXSIGDIG) /* can read it without overflow? */
+ r = (r * cast_num(16.0)) + luaO_hexavalue(*s);
+ else e++; /* too many digits; ignore, but still count for exponent */
+ if (dot) e--; /* decimal digit? correct exponent */
+ }
+ else break; /* neither a dot nor a digit */
+ }
+ if (nosigdig + sigdig == 0) /* no digits? */
+ return 0.0; /* invalid format */
+ *endptr = cast(char *, s); /* valid up to here */
+ e *= 4; /* each digit multiplies/divides value by 2^4 */
+ if (*s == 'p' || *s == 'P') { /* exponent part? */
+ int exp1 = 0; /* exponent value */
+ int neg1; /* exponent signal */
+ s++; /* skip 'p' */
+ neg1 = isneg(&s); /* signal */
+ if (!lisdigit(cast_uchar(*s)))
+ return 0.0; /* invalid; must have at least one digit */
+ while (lisdigit(cast_uchar(*s))) /* read exponent */
+ exp1 = exp1 * 10 + *(s++) - '0';
+ if (neg1) exp1 = -exp1;
+ e += exp1;
+ *endptr = cast(char *, s); /* valid up to here */
+ }
+ if (neg) r = -r;
+ return l_mathop(ldexp)(r, e);
+}
+
+#endif
+/* }====================================================== */
+
+
+static const char *l_str2d (const char *s, lua_Number *result) {
+ char *endptr;
+ if (strpbrk(s, "nN")) /* reject 'inf' and 'nan' */
+ return NULL;
+ else if (strpbrk(s, "xX")) /* hex? */
+ *result = lua_strx2number(s, &endptr);
+ else
+ *result = lua_str2number(s, &endptr);
+ if (endptr == s) return 0; /* nothing recognized */
+ while (lisspace(cast_uchar(*endptr))) endptr++;
+ return (*endptr == '\0' ? endptr : NULL); /* OK if no trailing characters */
+}
+
+
+static const char *l_str2int (const char *s, lua_Integer *result) {
+ lua_Unsigned a = 0;
+ int empty = 1;
+ int neg;
+ while (lisspace(cast_uchar(*s))) s++; /* skip initial spaces */
+ neg = isneg(&s);
+ if (s[0] == '0' &&
+ (s[1] == 'x' || s[1] == 'X')) { /* hex? */
+ s += 2; /* skip '0x' */
+ for (; lisxdigit(cast_uchar(*s)); s++) {
+ a = a * 16 + luaO_hexavalue(*s);
+ empty = 0;
+ }
+ }
+ else { /* decimal */
+ for (; lisdigit(cast_uchar(*s)); s++) {
+ a = a * 10 + *s - '0';
+ empty = 0;
+ }
+ }
+ while (lisspace(cast_uchar(*s))) s++; /* skip trailing spaces */
+ if (empty || *s != '\0') return NULL; /* something wrong in the numeral */
+ else {
+ *result = l_castU2S((neg) ? 0u - a : a);
+ return s;
+ }
+}
+
+
+size_t luaO_str2num (const char *s, TValue *o) {
+ lua_Integer i; lua_Number n;
+ const char *e;
+ if ((e = l_str2int(s, &i)) != NULL) { /* try as an integer */
+ setivalue(o, i);
+ }
+ else if ((e = l_str2d(s, &n)) != NULL) { /* else try as a float */
+ setfltvalue(o, n);
+ }
+ else
+ return 0; /* conversion failed */
+ return (e - s + 1); /* success; return string size */
+}
+
+
+int luaO_utf8esc (char *buff, unsigned long x) {
+ int n = 1; /* number of bytes put in buffer (backwards) */
+ lua_assert(x <= 0x10FFFF);
+ if (x < 0x80) /* ascii? */
+ buff[UTF8BUFFSZ - 1] = cast(char, x);
+ else { /* need continuation bytes */
+ unsigned int mfb = 0x3f; /* maximum that fits in first byte */
+ do { /* add continuation bytes */
+ buff[UTF8BUFFSZ - (n++)] = cast(char, 0x80 | (x & 0x3f));
+ x >>= 6; /* remove added bits */
+ mfb >>= 1; /* now there is one less bit available in first byte */
+ } while (x > mfb); /* still needs continuation byte? */
+ buff[UTF8BUFFSZ - n] = cast(char, (~mfb << 1) | x); /* add first byte */
+ }
+ return n;
+}
+
+
+/* maximum length of the conversion of a number to a string */
+#define MAXNUMBER2STR 50
+
+
+/*
+** Convert a number object to a string
+*/
+void luaO_tostring (lua_State *L, StkId obj) {
+ char buff[MAXNUMBER2STR];
+ size_t len;
+ lua_assert(ttisnumber(obj));
+ if (ttisinteger(obj))
+ len = lua_integer2str(buff, ivalue(obj));
+ else {
+ len = lua_number2str(buff, fltvalue(obj));
+#if !defined(LUA_COMPAT_FLOATSTRING)
+ if (buff[strspn(buff, "-0123456789")] == '\0') { /* looks like an int? */
+ buff[len++] = '.';
+ buff[len++] = '0'; /* adds '.0' to result */
+ }
+#endif
+ }
+ setsvalue2s(L, obj, luaS_newlstr(L, buff, len));
+}
+
+
+static void pushstr (lua_State *L, const char *str, size_t l) {
+ setsvalue2s(L, L->top++, luaS_newlstr(L, str, l));
+}
+
+
+/* this function handles only '%d', '%c', '%f', '%p', and '%s'
+ conventional formats, plus Lua-specific '%I' and '%U' */
+const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp) {
+ int n = 0;
+ for (;;) {
+ const char *e = strchr(fmt, '%');
+ if (e == NULL) break;
+ luaD_checkstack(L, 2); /* fmt + item */
+ pushstr(L, fmt, e - fmt);
+ switch (*(e+1)) {
+ case 's': {
+ const char *s = va_arg(argp, char *);
+ if (s == NULL) s = "(null)";
+ pushstr(L, s, strlen(s));
+ break;
+ }
+ case 'c': {
+ char buff = cast(char, va_arg(argp, int));
+ if (lisprint(cast_uchar(buff)))
+ pushstr(L, &buff, 1);
+ else /* non-printable character; print its code */
+ luaO_pushfstring(L, "<\\%d>", cast_uchar(buff));
+ break;
+ }
+ case 'd': {
+ setivalue(L->top++, va_arg(argp, int));
+ luaO_tostring(L, L->top - 1);
+ break;
+ }
+ case 'I': {
+ setivalue(L->top++, cast(lua_Integer, va_arg(argp, l_uacInt)));
+ luaO_tostring(L, L->top - 1);
+ break;
+ }
+ case 'f': {
+ setfltvalue(L->top++, cast_num(va_arg(argp, l_uacNumber)));
+ luaO_tostring(L, L->top - 1);
+ break;
+ }
+ case 'p': {
+ char buff[4*sizeof(void *) + 8]; /* should be enough space for a '%p' */
+ int l = sprintf(buff, "%p", va_arg(argp, void *));
+ pushstr(L, buff, l);
+ break;
+ }
+ case 'U': {
+ char buff[UTF8BUFFSZ];
+ int l = luaO_utf8esc(buff, cast(long, va_arg(argp, long)));
+ pushstr(L, buff + UTF8BUFFSZ - l, l);
+ break;
+ }
+ case '%': {
+ pushstr(L, "%", 1);
+ break;
+ }
+ default: {
+ luaG_runerror(L, "invalid option '%%%c' to 'lua_pushfstring'",
+ *(e + 1));
+ }
+ }
+ n += 2;
+ fmt = e+2;
+ }
+ luaD_checkstack(L, 1);
+ pushstr(L, fmt, strlen(fmt));
+ if (n > 0) luaV_concat(L, n + 1);
+ return svalue(L->top - 1);
+}
+
+
+const char *luaO_pushfstring (lua_State *L, const char *fmt, ...) {
+ const char *msg;
+ va_list argp;
+ va_start(argp, fmt);
+ msg = luaO_pushvfstring(L, fmt, argp);
+ va_end(argp);
+ return msg;
+}
+
+
+/* number of chars of a literal string without the ending \0 */
+#define LL(x) (sizeof(x)/sizeof(char) - 1)
+
+#define RETS "..."
+#define PRE "[string \""
+#define POS "\"]"
+
+#define addstr(a,b,l) ( memcpy(a,b,(l) * sizeof(char)), a += (l) )
+
+void luaO_chunkid (char *out, const char *source, size_t bufflen) {
+ size_t l = strlen(source);
+ if (*source == '=') { /* 'literal' source */
+ if (l <= bufflen) /* small enough? */
+ memcpy(out, source + 1, l * sizeof(char));
+ else { /* truncate it */
+ addstr(out, source + 1, bufflen - 1);
+ *out = '\0';
+ }
+ }
+ else if (*source == '@') { /* file name */
+ if (l <= bufflen) /* small enough? */
+ memcpy(out, source + 1, l * sizeof(char));
+ else { /* add '...' before rest of name */
+ addstr(out, RETS, LL(RETS));
+ bufflen -= LL(RETS);
+ memcpy(out, source + 1 + l - bufflen, bufflen * sizeof(char));
+ }
+ }
+ else { /* string; format as [string "source"] */
+ const char *nl = strchr(source, '\n'); /* find first new line (if any) */
+ addstr(out, PRE, LL(PRE)); /* add prefix */
+ bufflen -= LL(PRE RETS POS) + 1; /* save space for prefix+suffix+'\0' */
+ if (l < bufflen && nl == NULL) { /* small one-line source? */
+ addstr(out, source, l); /* keep it */
+ }
+ else {
+ if (nl != NULL) l = nl - source; /* stop at first newline */
+ if (l > bufflen) l = bufflen;
+ addstr(out, source, l);
+ addstr(out, RETS, LL(RETS));
+ }
+ memcpy(out, POS, (LL(POS) + 1) * sizeof(char));
+ }
+}
+
diff --git a/src/lobject.h b/src/lobject.h
new file mode 100644
index 0000000000..d7d0ebf31b
--- /dev/null
+++ b/src/lobject.h
@@ -0,0 +1,540 @@
+/*
+** $Id: lobject.h,v 2.106 2015/01/05 13:52:37 roberto Exp $
+** Type definitions for Lua objects
+** See Copyright Notice in lua.h
+*/
+
+
+#ifndef lobject_h
+#define lobject_h
+
+
+#include
+
+
+#include "llimits.h"
+#include "lua.h"
+
+
+/*
+** Extra tags for non-values
+*/
+#define LUA_TPROTO LUA_NUMTAGS
+#define LUA_TDEADKEY (LUA_NUMTAGS+1)
+
+/*
+** number of all possible tags (including LUA_TNONE but excluding DEADKEY)
+*/
+#define LUA_TOTALTAGS (LUA_TPROTO + 2)
+
+
+/*
+** tags for Tagged Values have the following use of bits:
+** bits 0-3: actual tag (a LUA_T* value)
+** bits 4-5: variant bits
+** bit 6: whether value is collectable
+*/
+
+#define VARBITS (3 << 4)
+
+
+/*
+** LUA_TFUNCTION variants:
+** 0 - Lua function
+** 1 - light C function
+** 2 - regular C function (closure)
+*/
+
+/* Variant tags for functions */
+#define LUA_TLCL (LUA_TFUNCTION | (0 << 4)) /* Lua closure */
+#define LUA_TLCF (LUA_TFUNCTION | (1 << 4)) /* light C function */
+#define LUA_TCCL (LUA_TFUNCTION | (2 << 4)) /* C closure */
+
+
+/* Variant tags for strings */
+#define LUA_TSHRSTR (LUA_TSTRING | (0 << 4)) /* short strings */
+#define LUA_TLNGSTR (LUA_TSTRING | (1 << 4)) /* long strings */
+
+
+/* Variant tags for numbers */
+#define LUA_TNUMFLT (LUA_TNUMBER | (0 << 4)) /* float numbers */
+#define LUA_TNUMINT (LUA_TNUMBER | (1 << 4)) /* integer numbers */
+
+
+/* Bit mark for collectable types */
+#define BIT_ISCOLLECTABLE (1 << 6)
+
+/* mark a tag as collectable */
+#define ctb(t) ((t) | BIT_ISCOLLECTABLE)
+
+
+/*
+** Common type for all collectable objects
+*/
+typedef struct GCObject GCObject;
+
+
+/*
+** Common Header for all collectable objects (in macro form, to be
+** included in other objects)
+*/
+#define CommonHeader GCObject *next; lu_byte tt; lu_byte marked
+
+
+/*
+** Common type has only the common header
+*/
+struct GCObject {
+ CommonHeader;
+};
+
+
+
+/*
+** Union of all Lua values
+*/
+typedef union Value Value;
+
+
+
+
+/*
+** Tagged Values. This is the basic representation of values in Lua,
+** an actual value plus a tag with its type.
+*/
+
+#define TValuefields Value value_; int tt_
+
+typedef struct lua_TValue TValue;
+
+
+/* macro defining a nil value */
+#define NILCONSTANT {NULL}, LUA_TNIL
+
+
+#define val_(o) ((o)->value_)
+
+
+/* raw type tag of a TValue */
+#define rttype(o) ((o)->tt_)
+
+/* tag with no variants (bits 0-3) */
+#define novariant(x) ((x) & 0x0F)
+
+/* type tag of a TValue (bits 0-3 for tags + variant bits 4-5) */
+#define ttype(o) (rttype(o) & 0x3F)
+
+/* type tag of a TValue with no variants (bits 0-3) */
+#define ttnov(o) (novariant(rttype(o)))
+
+
+/* Macros to test type */
+#define checktag(o,t) (rttype(o) == (t))
+#define checktype(o,t) (ttnov(o) == (t))
+#define ttisnumber(o) checktype((o), LUA_TNUMBER)
+#define ttisfloat(o) checktag((o), LUA_TNUMFLT)
+#define ttisinteger(o) checktag((o), LUA_TNUMINT)
+#define ttisnil(o) checktag((o), LUA_TNIL)
+#define ttisboolean(o) checktag((o), LUA_TBOOLEAN)
+#define ttislightuserdata(o) checktag((o), LUA_TLIGHTUSERDATA)
+#define ttisstring(o) checktype((o), LUA_TSTRING)
+#define ttisshrstring(o) checktag((o), ctb(LUA_TSHRSTR))
+#define ttislngstring(o) checktag((o), ctb(LUA_TLNGSTR))
+#define ttistable(o) checktag((o), ctb(LUA_TTABLE))
+#define ttisfunction(o) checktype(o, LUA_TFUNCTION)
+#define ttisclosure(o) ((rttype(o) & 0x1F) == LUA_TFUNCTION)
+#define ttisCclosure(o) checktag((o), ctb(LUA_TCCL))
+#define ttisLclosure(o) checktag((o), ctb(LUA_TLCL))
+#define ttislcf(o) checktag((o), LUA_TLCF)
+#define ttisfulluserdata(o) checktag((o), ctb(LUA_TUSERDATA))
+#define ttisthread(o) checktag((o), ctb(LUA_TTHREAD))
+#define ttisdeadkey(o) checktag((o), LUA_TDEADKEY)
+
+
+/* Macros to access values */
+#define ivalue(o) check_exp(ttisinteger(o), val_(o).i)
+#define fltvalue(o) check_exp(ttisfloat(o), val_(o).n)
+#define nvalue(o) check_exp(ttisnumber(o), \
+ (ttisinteger(o) ? cast_num(ivalue(o)) : fltvalue(o)))
+#define gcvalue(o) check_exp(iscollectable(o), val_(o).gc)
+#define pvalue(o) check_exp(ttislightuserdata(o), val_(o).p)
+#define tsvalue(o) check_exp(ttisstring(o), gco2ts(val_(o).gc))
+#define uvalue(o) check_exp(ttisfulluserdata(o), gco2u(val_(o).gc))
+#define clvalue(o) check_exp(ttisclosure(o), gco2cl(val_(o).gc))
+#define clLvalue(o) check_exp(ttisLclosure(o), gco2lcl(val_(o).gc))
+#define clCvalue(o) check_exp(ttisCclosure(o), gco2ccl(val_(o).gc))
+#define fvalue(o) check_exp(ttislcf(o), val_(o).f)
+#define hvalue(o) check_exp(ttistable(o), gco2t(val_(o).gc))
+#define bvalue(o) check_exp(ttisboolean(o), val_(o).b)
+#define thvalue(o) check_exp(ttisthread(o), gco2th(val_(o).gc))
+/* a dead value may get the 'gc' field, but cannot access its contents */
+#define deadvalue(o) check_exp(ttisdeadkey(o), cast(void *, val_(o).gc))
+
+#define l_isfalse(o) (ttisnil(o) || (ttisboolean(o) && bvalue(o) == 0))
+
+
+#define iscollectable(o) (rttype(o) & BIT_ISCOLLECTABLE)
+
+
+/* Macros for internal tests */
+#define righttt(obj) (ttype(obj) == gcvalue(obj)->tt)
+
+#define checkliveness(g,obj) \
+ lua_longassert(!iscollectable(obj) || \
+ (righttt(obj) && !isdead(g,gcvalue(obj))))
+
+
+/* Macros to set values */
+#define settt_(o,t) ((o)->tt_=(t))
+
+#define setfltvalue(obj,x) \
+ { TValue *io=(obj); val_(io).n=(x); settt_(io, LUA_TNUMFLT); }
+
+#define setivalue(obj,x) \
+ { TValue *io=(obj); val_(io).i=(x); settt_(io, LUA_TNUMINT); }
+
+#define setnilvalue(obj) settt_(obj, LUA_TNIL)
+
+#define setfvalue(obj,x) \
+ { TValue *io=(obj); val_(io).f=(x); settt_(io, LUA_TLCF); }
+
+#define setpvalue(obj,x) \
+ { TValue *io=(obj); val_(io).p=(x); settt_(io, LUA_TLIGHTUSERDATA); }
+
+#define setbvalue(obj,x) \
+ { TValue *io=(obj); val_(io).b=(x); settt_(io, LUA_TBOOLEAN); }
+
+#define setgcovalue(L,obj,x) \
+ { TValue *io = (obj); GCObject *i_g=(x); \
+ val_(io).gc = i_g; settt_(io, ctb(i_g->tt)); }
+
+#define setsvalue(L,obj,x) \
+ { TValue *io = (obj); TString *x_ = (x); \
+ val_(io).gc = obj2gco(x_); settt_(io, ctb(x_->tt)); \
+ checkliveness(G(L),io); }
+
+#define setuvalue(L,obj,x) \
+ { TValue *io = (obj); Udata *x_ = (x); \
+ val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_TUSERDATA)); \
+ checkliveness(G(L),io); }
+
+#define setthvalue(L,obj,x) \
+ { TValue *io = (obj); lua_State *x_ = (x); \
+ val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_TTHREAD)); \
+ checkliveness(G(L),io); }
+
+#define setclLvalue(L,obj,x) \
+ { TValue *io = (obj); LClosure *x_ = (x); \
+ val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_TLCL)); \
+ checkliveness(G(L),io); }
+
+#define setclCvalue(L,obj,x) \
+ { TValue *io = (obj); CClosure *x_ = (x); \
+ val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_TCCL)); \
+ checkliveness(G(L),io); }
+
+#define sethvalue(L,obj,x) \
+ { TValue *io = (obj); Table *x_ = (x); \
+ val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_TTABLE)); \
+ checkliveness(G(L),io); }
+
+#define setdeadvalue(obj) settt_(obj, LUA_TDEADKEY)
+
+
+
+#define setobj(L,obj1,obj2) \
+ { TValue *io1=(obj1); *io1 = *(obj2); \
+ (void)L; checkliveness(G(L),io1); }
+
+
+/*
+** different types of assignments, according to destination
+*/
+
+/* from stack to (same) stack */
+#define setobjs2s setobj
+/* to stack (not from same stack) */
+#define setobj2s setobj
+#define setsvalue2s setsvalue
+#define sethvalue2s sethvalue
+#define setptvalue2s setptvalue
+/* from table to same table */
+#define setobjt2t setobj
+/* to table */
+#define setobj2t setobj
+/* to new object */
+#define setobj2n setobj
+#define setsvalue2n setsvalue
+
+
+
+
+/*
+** {======================================================
+** types and prototypes
+** =======================================================
+*/
+
+
+union Value {
+ GCObject *gc; /* collectable objects */
+ void *p; /* light userdata */
+ int b; /* booleans */
+ lua_CFunction f; /* light C functions */
+ lua_Integer i; /* integer numbers */
+ lua_Number n; /* float numbers */
+};
+
+
+struct lua_TValue {
+ TValuefields;
+};
+
+
+typedef TValue *StkId; /* index to stack elements */
+
+
+
+
+/*
+** Header for string value; string bytes follow the end of this structure
+** (aligned according to 'UTString'; see next).
+*/
+typedef struct TString {
+ CommonHeader;
+ lu_byte extra; /* reserved words for short strings; "has hash" for longs */
+ unsigned int hash;
+ size_t len; /* number of characters in string */
+ struct TString *hnext; /* linked list for hash table */
+} TString;
+
+
+/*
+** Ensures that address after this type is always fully aligned.
+*/
+typedef union UTString {
+ L_Umaxalign dummy; /* ensures maximum alignment for strings */
+ TString tsv;
+} UTString;
+
+
+/*
+** Get the actual string (array of bytes) from a 'TString'.
+** (Access to 'extra' ensures that value is really a 'TString'.)
+*/
+#define getaddrstr(ts) (cast(char *, (ts)) + sizeof(UTString))
+#define getstr(ts) \
+ check_exp(sizeof((ts)->extra), cast(const char*, getaddrstr(ts)))
+
+/* get the actual string (array of bytes) from a Lua value */
+#define svalue(o) getstr(tsvalue(o))
+
+
+/*
+** Header for userdata; memory area follows the end of this structure
+** (aligned according to 'UUdata'; see next).
+*/
+typedef struct Udata {
+ CommonHeader;
+ lu_byte ttuv_; /* user value's tag */
+ struct Table *metatable;
+ size_t len; /* number of bytes */
+ union Value user_; /* user value */
+} Udata;
+
+
+/*
+** Ensures that address after this type is always fully aligned.
+*/
+typedef union UUdata {
+ L_Umaxalign dummy; /* ensures maximum alignment for 'local' udata */
+ Udata uv;
+} UUdata;
+
+
+/*
+** Get the address of memory block inside 'Udata'.
+** (Access to 'ttuv_' ensures that value is really a 'Udata'.)
+*/
+#define getudatamem(u) \
+ check_exp(sizeof((u)->ttuv_), (cast(char*, (u)) + sizeof(UUdata)))
+
+#define setuservalue(L,u,o) \
+ { const TValue *io=(o); Udata *iu = (u); \
+ iu->user_ = io->value_; iu->ttuv_ = io->tt_; \
+ checkliveness(G(L),io); }
+
+
+#define getuservalue(L,u,o) \
+ { TValue *io=(o); const Udata *iu = (u); \
+ io->value_ = iu->user_; io->tt_ = iu->ttuv_; \
+ checkliveness(G(L),io); }
+
+
+/*
+** Description of an upvalue for function prototypes
+*/
+typedef struct Upvaldesc {
+ TString *name; /* upvalue name (for debug information) */
+ lu_byte instack; /* whether it is in stack */
+ lu_byte idx; /* index of upvalue (in stack or in outer function's list) */
+} Upvaldesc;
+
+
+/*
+** Description of a local variable for function prototypes
+** (used for debug information)
+*/
+typedef struct LocVar {
+ TString *varname;
+ int startpc; /* first point where variable is active */
+ int endpc; /* first point where variable is dead */
+} LocVar;
+
+
+/*
+** Function Prototypes
+*/
+typedef struct Proto {
+ CommonHeader;
+ lu_byte numparams; /* number of fixed parameters */
+ lu_byte is_vararg;
+ lu_byte maxstacksize; /* maximum stack used by this function */
+ int sizeupvalues; /* size of 'upvalues' */
+ int sizek; /* size of 'k' */
+ int sizecode;
+ int sizelineinfo;
+ int sizep; /* size of 'p' */
+ int sizelocvars;
+ int linedefined;
+ int lastlinedefined;
+ TValue *k; /* constants used by the function */
+ Instruction *code;
+ struct Proto **p; /* functions defined inside the function */
+ int *lineinfo; /* map from opcodes to source lines (debug information) */
+ LocVar *locvars; /* information about local variables (debug information) */
+ Upvaldesc *upvalues; /* upvalue information */
+ struct LClosure *cache; /* last created closure with this prototype */
+ TString *source; /* used for debug information */
+ GCObject *gclist;
+} Proto;
+
+
+
+/*
+** Lua Upvalues
+*/
+typedef struct UpVal UpVal;
+
+
+/*
+** Closures
+*/
+
+#define ClosureHeader \
+ CommonHeader; lu_byte nupvalues; GCObject *gclist
+
+typedef struct CClosure {
+ ClosureHeader;
+ lua_CFunction f;
+ TValue upvalue[1]; /* list of upvalues */
+} CClosure;
+
+
+typedef struct LClosure {
+ ClosureHeader;
+ struct Proto *p;
+ UpVal *upvals[1]; /* list of upvalues */
+} LClosure;
+
+
+typedef union Closure {
+ CClosure c;
+ LClosure l;
+} Closure;
+
+
+#define isLfunction(o) ttisLclosure(o)
+
+#define getproto(o) (clLvalue(o)->p)
+
+
+/*
+** Tables
+*/
+
+typedef union TKey {
+ struct {
+ TValuefields;
+ int next; /* for chaining (offset for next node) */
+ } nk;
+ TValue tvk;
+} TKey;
+
+
+/* copy a value into a key without messing up field 'next' */
+#define setnodekey(L,key,obj) \
+ { TKey *k_=(key); const TValue *io_=(obj); \
+ k_->nk.value_ = io_->value_; k_->nk.tt_ = io_->tt_; \
+ (void)L; checkliveness(G(L),io_); }
+
+
+typedef struct Node {
+ TValue i_val;
+ TKey i_key;
+} Node;
+
+
+typedef struct Table {
+ CommonHeader;
+ lu_byte flags; /* 1<