xLua - Lua C++ API

Check-in [9ebeabe199]
Login
Overview
Comment:xlua
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | master | trunk
Files: files | file ages | folders
SHA3-256:9ebeabe1996d243973563d15b7bf7144622dfa38b35dbdd0f3a414092c71c073
User & Date: xjail 2018-07-05 21:11:53
Context
2018-07-12
02:21
update check-in: 1152ce8736 user: xjail tags: master, trunk
2018-07-05
21:11
xlua check-in: 9ebeabe199 user: xjail tags: master, trunk
2018-07-04
21:16
xlua check-in: 14a84d3be5 user: xjail tags: master, trunk
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Changes to AUTHORS.





1




* Julio Merino <jmmv@google.com>
>
>
>
>

1
2
3
4
5
xlua:
xjail.tiv.cc developers

lutok:
* Julio Merino <jmmv@google.com>

Added INSTALL.













































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
REQUIREMENTS
============

lua 5.2, 5.3, +
BSD make or bmake, mk-files



1. BUILD
========

Build with common user:
$ cd xlua
$ make
This will build libxlua.so in xlua/src and build examples.



2. INSTALL
==========

Copy xlua/include and xlua/src/libxlua.a to your system.

Added Makefile.









>
>
>
>
1
2
3
4
SUBDIR += src
SUBDIR += examples

.include <bsd.subdir.mk>

Changes to NEWS.















1
2
3
4
5
6
7














Changes in version 0.4
======================

Released on 2013/12/07.

* Cope with the lack of AM_PROG_AR in configure.ac, which first
  appeared in Automake 1.11.2.  Fixes a problem in Ubuntu 10.04
>
>
>
>
>
>
>
>
>
>
>
>
>
>







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
xLua forks from lutok
=====================

on 2018/07/04.






lutok
=====


Changes in version 0.4
======================

Released on 2013/12/07.

* Cope with the lack of AM_PROG_AR in configure.ac, which first
  appeared in Automake 1.11.2.  Fixes a problem in Ubuntu 10.04

Deleted c_gate.cpp.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// Copyright 2011 Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
//   notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
//   notice, this list of conditions and the following disclaimer in the
//   documentation and/or other materials provided with the distribution.
// * Neither the name of Google Inc. nor the names of its contributors
//   may be used to endorse or promote products derived from this software
//   without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "c_gate.hpp"
#include "state.ipp"


/// Creates a new gateway to an existing C++ Lua state.
///
/// \param state_ The state to connect to.  This object must remain alive while
///     the newly-constructed state_c_gate is alive.
lutok::state_c_gate::state_c_gate(state& state_) :
    _state(state_)
{
}


/// Destructor.
///
/// Destroying this object has no implications on the life cycle of the Lua
/// state.  Only the corresponding state object controls when the Lua state is
/// closed.
lutok::state_c_gate::~state_c_gate(void)
{
}


/// Creates a C++ state for a C Lua state.
///
/// \warning The created state object does NOT own the C state.  You must take
/// care to properly destroy the input lua_State when you are done with it to
/// not leak resources.
///
/// \param raw_state The raw state to wrap temporarily.
///
/// \return The wrapped state without strong ownership on the input state.
lutok::state
lutok::state_c_gate::connect(lua_State* raw_state)
{
    return state(static_cast< void* >(raw_state));
}


/// Returns the C native Lua state.
///
/// \return A native lua_State object holding the Lua C API state.
lua_State*
lutok::state_c_gate::c_state(void)
{
    return static_cast< lua_State* >(_state.raw_state());
}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
























































































































































Added compiler.config.











>
>
>
>
>
1
2
3
4
5
CXXFLAGS += -std=c++14 -stdlib=libc++
LDFLAGS += -lc++ -lm -lthr -pthread
CC = clang
CXX = clang++
CPP = clang-cpp

Deleted debug.cpp.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
// Copyright 2011 Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
//   notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
//   notice, this list of conditions and the following disclaimer in the
//   documentation and/or other materials provided with the distribution.
// * Neither the name of Google Inc. nor the names of its contributors
//   may be used to endorse or promote products derived from this software
//   without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include <cassert>

#include <lua.hpp>

#include <xlua/c_gate.hpp>
#include <xlua/debug.hpp>
#include <xlua/exceptions.hpp>
#include <xlua/state.ipp>


/// Internal implementation for lutok::debug.
struct lutok::debug::impl {
    /// The Lua internal debug state.
    lua_Debug lua_debug;
};


/// Constructor for an empty debug structure.
lutok::debug::debug(void) :
    _pimpl(new impl())
{
}


/// Destructor.
lutok::debug::~debug(void)
{
}


/// Wrapper around lua_getinfo.
///
/// \param s The Lua state.
/// \param what_ The second parameter to lua_getinfo.
///
/// \warning Terminates execution if there is not enough memory to manipulate
/// the Lua stack.
void
lutok::debug::get_info(state& s, const std::string& what_)
{
    lua_State* raw_state = state_c_gate(s).c_state();

    if (lua_getinfo(raw_state, what_.c_str(), &_pimpl->lua_debug) == 0)
        throw lutok::api_error::from_stack(s, "lua_getinfo");
}


/// Wrapper around lua_getstack.
///
/// \param s The Lua state.
/// \param level The second parameter to lua_getstack.
void
lutok::debug::get_stack(state& s, const int level)
{
    lua_State* raw_state = state_c_gate(s).c_state();

    lua_getstack(raw_state, level, &_pimpl->lua_debug);
}


/// Accessor for the 'event' field of lua_Debug.
///
/// \return Returns the 'event' field of the internal lua_Debug structure.
int
lutok::debug::event(void) const
{
    return _pimpl->lua_debug.event;
}


/// Accessor for the 'name' field of lua_Debug.
///
/// \return Returns the 'name' field of the internal lua_Debug structure.
std::string
lutok::debug::name(void) const
{
    assert(_pimpl->lua_debug.name != NULL);
    return _pimpl->lua_debug.name;
}


/// Accessor for the 'namewhat' field of lua_Debug.
///
/// \return Returns the 'namewhat' field of the internal lua_Debug structure.
std::string
lutok::debug::name_what(void) const
{
    assert(_pimpl->lua_debug.namewhat != NULL);
    return _pimpl->lua_debug.namewhat;
}


/// Accessor for the 'what' field of lua_Debug.
///
/// \return Returns the 'what' field of the internal lua_Debug structure.
std::string
lutok::debug::what(void) const
{
    assert(_pimpl->lua_debug.what != NULL);
    return _pimpl->lua_debug.what;
}


/// Accessor for the 'source' field of lua_Debug.
///
/// \return Returns the 'source' field of the internal lua_Debug structure.
std::string
lutok::debug::source(void) const
{
    assert(_pimpl->lua_debug.source != NULL);
    return _pimpl->lua_debug.source;
}


/// Accessor for the 'currentline' field of lua_Debug.
///
/// \return Returns the 'currentline' field of the internal lua_Debug structure.
int
lutok::debug::current_line(void) const
{
    return _pimpl->lua_debug.currentline;
}


/// Accessor for the 'nups' field of lua_Debug.
///
/// \return Returns the 'nups' field of the internal lua_Debug structure.
int
lutok::debug::n_ups(void) const
{
    return _pimpl->lua_debug.nups;
}


/// Accessor for the 'linedefined' field of lua_Debug.
///
/// \return Returns the 'linedefined' field of the internal lua_Debug structure.
int
lutok::debug::line_defined(void) const
{
    return _pimpl->lua_debug.linedefined;
}


/// Accessor for the 'lastlinedefined' field of lua_Debug.
///
/// \return Returns the 'lastlinedefined' field of the internal lua_Debug
/// structure.
int
lutok::debug::last_line_defined(void) const
{
    return _pimpl->lua_debug.lastlinedefined;
}


/// Accessor for the 'short_src' field of lua_Debug.
///
/// \return Returns the 'short_src' field of the internal lua_Debug structure.
std::string
lutok::debug::short_src(void) const
{
    assert(_pimpl->lua_debug.short_src != NULL);
    return _pimpl->lua_debug.short_src;
}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
































































































































































































































































































































































































Changes to examples/Makefile.

1
2
3
4
5
6

7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27




28
29
30
31
32
33



34
35
36
37
38
39

40
41
42
43
44
45
46


47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67


# Copyright 2012 Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:

#
# * Redistributions of source code must retain the above copyright
#   notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
#   notice, this list of conditions and the following disclaimer in the
#   documentation and/or other materials provided with the distribution.
# * Neither the name of Google Inc. nor the names of its contributors
#   may be used to endorse or promote products derived from this software
#   without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.





CXX ?= c++
CPPFLAGS ?=
CXXFLAGS ?= -Wall -O2
LDFLAGS ?=
LIBS ?=




LUTOK_CPPFLAGS = $$(pkg-config --cflags-only-I lutok)
LUTOK_CXXFLAGS = $$(pkg-config --cflags-only-other lutok)
LUTOK_LDFLAGS = $$(pkg-config --libs-only-L lutok) \
                $$(pkg-config --libs-only-other lutok)
LUTOK_LIBS = $$(pkg-config --libs-only-l lutok)


BUILD = $(CXX) \
        $(CPPFLAGS) $(LUTOK_CPPFLAGS) \
        $(CXXFLAGS) $(LUTOK_CXXFLAGS) \
        $(LDFLAGS) $(LUTOK_LDFLAGS) \
        -o $${target} $${source} \
        $(LIBS) $(LUTOK_LIBS)



PROGRAMS = bindings hello interpreter raii

.PHONY: all
all: $(PROGRAMS)

bindings: bindings.cpp
	@target=bindings source=bindings.cpp; echo $(BUILD); $(BUILD)

hello: hello.cpp
	@target=hello source=hello.cpp; echo $(BUILD); $(BUILD)

interpreter: interpreter.cpp
	@target=interpreter source=interpreter.cpp; echo $(BUILD); $(BUILD)

raii: raii.cpp
	@target=raii source=raii.cpp; echo $(BUILD); $(BUILD)

.PHONY: clean
clean:
	rm -f $(PROGRAMS)


<
<

<
<
<
>

<
<
<
<
<
<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
>
>
>
>

<
<
<
<
<
>
>
>

<
<
<
<
<
>

<
<
<
<
<
<
>
>

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
>
>


1



2
3








4











5
6
7
8
9





10
11
12
13





14
15






16
17
18




















19
20


#



# Copyright (c) 2018 xjail.tiv.cc
#




















sources = bindings.cpp hello.cpp interpreter.cpp raii.cpp
.for source in ${sources}
PROGS += ${source:S/.cpp$//1}
.endfor






.for PROG in ${PROGS}
SRCS.${PROG} = ${PROG}.cpp
.endfor






MAN =







CXXFLAGS += -I../include `pkgconf --cflags lua-5.3`
LDFLAGS += -L../src -lxlua `pkgconf --libs lua-5.3`





















.include "../compiler.config"
.include <bsd.progs.mk>

Changes to examples/bindings.cpp.

70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
...
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
///
/// \param state The Lua state from which to get the function arguments and into
///     which to push the results.
///
/// \return The number of results pushed onto the stack, i.e. 1.
///
/// \throw std::runtime_error If the input parameters are invalid.  Note that
///     Lutok will convert this exception to lutok::error.
static int
lua_factorial(lutok::state& state)
{
    if (!state.is_number(-1))
        throw std::runtime_error("Argument to factorial must be an integer");
    const int i = state.to_integer(-1);
    if (i < 0)
        throw std::runtime_error("Argument to factorial must be positive");
    state.push_integer(factorial(i));
................................................................................
{
    if (argc != 2) {
        std::cerr << "Usage: bindings <number>\n";
        return EXIT_FAILURE;
    }

    // Create a new Lua session and load the print() function.
    lutok::state state;
    state.open_base();

    // Construct a 'module' that contains an entry point to our native factorial
    // function.  A module is just a Lua table that contains a mapping of names
    // to functions.  Instead of creating a module by using our create_module()
    // helper function, we could have used push_cxx_function on the state to
    // define the function ourselves.
    std::map< std::string, lutok::cxx_function > module;
    module["factorial"] = lua_factorial;
    lutok::create_module(state, "native", module);

    // Use a little Lua script to call our native factorial function providing
    // it the first argument passed to the program.  Note that this will error
    // out in a controlled manner if the passed argument is not an integer.  The
    // important thing to notice is that the exception comes from our own C++
    // binding and that it has been converted to a lutok::error.
    std::ostringstream script;
    script << "print(native.factorial(" << argv[1] << "))";
    try {
        lutok::do_string(state, script.str(), 0, 0, 0);
        return EXIT_SUCCESS;
    } catch (const lutok::error& e) {
        std::cerr << "ERROR: " << e.what() << '\n';
        return EXIT_FAILURE;
    }
}







|

|







 







|







|

|





|



|

|




70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
...
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
///
/// \param state The Lua state from which to get the function arguments and into
///     which to push the results.
///
/// \return The number of results pushed onto the stack, i.e. 1.
///
/// \throw std::runtime_error If the input parameters are invalid.  Note that
///     Lutok will convert this exception to xlua::error.
static int
lua_factorial(xlua::state& state)
{
    if (!state.is_number(-1))
        throw std::runtime_error("Argument to factorial must be an integer");
    const int i = state.to_integer(-1);
    if (i < 0)
        throw std::runtime_error("Argument to factorial must be positive");
    state.push_integer(factorial(i));
................................................................................
{
    if (argc != 2) {
        std::cerr << "Usage: bindings <number>\n";
        return EXIT_FAILURE;
    }

    // Create a new Lua session and load the print() function.
    xlua::state state;
    state.open_base();

    // Construct a 'module' that contains an entry point to our native factorial
    // function.  A module is just a Lua table that contains a mapping of names
    // to functions.  Instead of creating a module by using our create_module()
    // helper function, we could have used push_cxx_function on the state to
    // define the function ourselves.
    std::map< std::string, xlua::cxx_function > module;
    module["factorial"] = lua_factorial;
    xlua::create_module(state, "native", module);

    // Use a little Lua script to call our native factorial function providing
    // it the first argument passed to the program.  Note that this will error
    // out in a controlled manner if the passed argument is not an integer.  The
    // important thing to notice is that the exception comes from our own C++
    // binding and that it has been converted to a xlua::error.
    std::ostringstream script;
    script << "print(native.factorial(" << argv[1] << "))";
    try {
        xlua::do_string(state, script.str(), 0, 0, 0);
        return EXIT_SUCCESS;
    } catch (const xlua::error& e) {
        std::cerr << "ERROR: " << e.what() << '\n';
        return EXIT_FAILURE;
    }
}

Changes to examples/hello.cpp.

38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
///
/// \return A system exit code.
int
main(void)
{
    // Initializes a new Lua state.  Every Lua state is independent from each
    // other.
    lutok::state state;

    // Loads the standard library into the Lua state.  Among many other
    // functions, this gives us access to print(), which is used below.
    state.open_base();

    // Pushes the print() function into the Lua stack, then its only argument,
    // and then proceeds to execute it within the Lua state.
    state.get_global("print");
    state.push_string("Hello, world!");
    state.pcall(1, 0, 0);

    return EXIT_SUCCESS;
}







|













38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
///
/// \return A system exit code.
int
main(void)
{
    // Initializes a new Lua state.  Every Lua state is independent from each
    // other.
    xlua::state state;

    // Loads the standard library into the Lua state.  Among many other
    // functions, this gives us access to print(), which is used below.
    state.open_base();

    // Pushes the print() function into the Lua stack, then its only argument,
    // and then proceeds to execute it within the Lua state.
    state.get_global("print");
    state.push_string("Hello, world!");
    state.pcall(1, 0, 0);

    return EXIT_SUCCESS;
}

Changes to examples/interpreter.cpp.

39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74


/// Executes a Lua statement provided by the user with error checking.
///
/// \param state The Lua state in which to process the statement.
/// \param line The textual statement provided by the user.
static void
run_statement(lutok::state& state, const std::string& line)
{
    try {
        // This utility function allows us to feed a given piece of Lua code to
        // the interpreter and process it.  The piece of code can include
        // multiple statements separated by a semicolon or by a newline
        // character.
        lutok::do_string(state, line, 0, 0, 0);
    } catch (const lutok::error& error) {
        std::cerr << "ERROR: " << error.what() << '\n';
    }
}


/// Program's entry point.
///
/// \return A system exit code.
int
main(void)
{
    // Create a new session and load some standard libraries.
    lutok::state state;
    state.open_base();
    state.open_string();
    state.open_table();

    for (;;) {
        std::cout << "lua> ";
        std::cout.flush();







|






|
|












|







39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74


/// Executes a Lua statement provided by the user with error checking.
///
/// \param state The Lua state in which to process the statement.
/// \param line The textual statement provided by the user.
static void
run_statement(xlua::state& state, const std::string& line)
{
    try {
        // This utility function allows us to feed a given piece of Lua code to
        // the interpreter and process it.  The piece of code can include
        // multiple statements separated by a semicolon or by a newline
        // character.
        xlua::do_string(state, line, 0, 0, 0);
    } catch (const xlua::error& error) {
        std::cerr << "ERROR: " << error.what() << '\n';
    }
}


/// Program's entry point.
///
/// \return A system exit code.
int
main(void)
{
    // Create a new session and load some standard libraries.
    xlua::state state;
    state.open_base();
    state.open_string();
    state.open_table();

    for (;;) {
        std::cout << "lua> ";
        std::cout.flush();

Changes to examples/raii.cpp.

55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
...
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
/// If the field contains a string, this function prints its value.  If the
/// field contains any other type, this prints an error message.
///
/// \pre The top of the Lua stack in 'state' references a table.
///
/// \param state The Lua state.
/// \param field The name of the string-typed field.
static void
print_table_field(lutok::state& state, const std::string& field)
{
    assert(state.is_table(-1));

    // Bring in some RAII magic: the stack_cleaner object captures the current
    // height of the Lua stack at this point.  Whenever the object goes out of
    // scope, it will pop as many entries from the stack as necessary to restore
    // the stack to its previous level.
    //
    // This ensures that, no matter how we exit the function, we do not leak
    // objects in the stack.
    lutok::stack_cleaner cleaner(state);

    // Stack contents: -1: table.
    state.push_string(field);
    // Stack contents: -2: table, -1: field name.
    state.get_table(-2);
    // Stack contents: -2: table, -1: field value.

................................................................................

/// Program's entry point.
///
/// \return A system exit code.
int
main(void)
{
    lutok::state state;
    state.open_base();

    lutok::do_string(state, "example = {foo='hello', bar=123, baz='bye'}",
                     0, 0, 0);

    state.get_global("example");
    print_table_field(state, "foo");
    print_table_field(state, "bar");
    print_table_field(state, "baz");
    state.pop(1);

    return EXIT_SUCCESS;
}







<
|










|







 







|


|










55
56
57
58
59
60
61

62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
...
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
/// If the field contains a string, this function prints its value.  If the
/// field contains any other type, this prints an error message.
///
/// \pre The top of the Lua stack in 'state' references a table.
///
/// \param state The Lua state.
/// \param field The name of the string-typed field.

static void print_table_field(xlua::state& state, const std::string& field)
{
    assert(state.is_table(-1));

    // Bring in some RAII magic: the stack_cleaner object captures the current
    // height of the Lua stack at this point.  Whenever the object goes out of
    // scope, it will pop as many entries from the stack as necessary to restore
    // the stack to its previous level.
    //
    // This ensures that, no matter how we exit the function, we do not leak
    // objects in the stack.
    xlua::stack_cleaner cleaner(state);

    // Stack contents: -1: table.
    state.push_string(field);
    // Stack contents: -2: table, -1: field name.
    state.get_table(-2);
    // Stack contents: -2: table, -1: field value.

................................................................................

/// Program's entry point.
///
/// \return A system exit code.
int
main(void)
{
    xlua::state state;
    state.open_base();

    xlua::do_string(state, "example = {foo='hello', bar=123, baz='bye'}",
                     0, 0, 0);

    state.get_global("example");
    print_table_field(state, "foo");
    print_table_field(state, "bar");
    print_table_field(state, "baz");
    state.pop(1);

    return EXIT_SUCCESS;
}

Deleted exceptions.cpp.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
// Copyright 2011 Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
//   notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
//   notice, this list of conditions and the following disclaimer in the
//   documentation and/or other materials provided with the distribution.
// * Neither the name of Google Inc. nor the names of its contributors
//   may be used to endorse or promote products derived from this software
//   without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include <cassert>

#include <lua.hpp>

#include "c_gate.hpp"
#include "exceptions.hpp"
#include "state.ipp"


/// Constructs a new error with a plain-text message.
///
/// \param message The plain-text error message.
lutok::error::error(const std::string& message) :
    std::runtime_error(message)
{
}


/// Destructor for the error.
lutok::error::~error(void) throw()
{
}


/// Constructs a new error.
///
/// \param api_function_ The name of the API function that caused the error.
/// \param message The plain-text error message provided by Lua.
lutok::api_error::api_error(const std::string& api_function_,
                            const std::string& message) :
    error(message),
    _api_function(api_function_)
{
}


/// Destructor for the error.
lutok::api_error::~api_error(void) throw()
{
}


/// Constructs a new api_error with the message on the top of the Lua stack.
///
/// \pre There is an error message on the top of the stack.
/// \post The error message is popped from the stack.
///
/// \param state_ The Lua state.
/// \param api_function_ The name of the Lua API function that caused the error.
///
/// \return A new api_error with the popped message.
lutok::api_error
lutok::api_error::from_stack(state& state_, const std::string& api_function_)
{
    lua_State* raw_state = lutok::state_c_gate(state_).c_state();

    assert(lua_isstring(raw_state, -1));
    const std::string message = lua_tostring(raw_state, -1);
    lua_pop(raw_state, 1);
    return lutok::api_error(api_function_, message);
}


/// Gets the name of the Lua API function that caused this error.
///
/// \return The name of the function.
const std::string&
lutok::api_error::api_function(void) const
{
    return _api_function;
}
 

/// Constructs a new error.
///
/// \param filename_ The file that count not be found.
lutok::file_not_found_error::file_not_found_error(
    const std::string& filename_) :
    error("File '" + filename_ + "' not found"),
    _filename(filename_)
{
}


/// Destructor for the error.
lutok::file_not_found_error::~file_not_found_error(void) throw()
{
}


/// Gets the name of the file that could not be found.
///
/// \return The name of the file.
const std::string&
lutok::file_not_found_error::filename(void) const
{
    return _filename;
}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




























































































































































































































































Changes to include/xlua/c_gate.hpp.

30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
..
62
63
64
65
66
67
68
69
70
71
/// Provides direct access to the C state of the Lua wrappers.

#if !defined(LUTOK_C_GATE_HPP)
#define LUTOK_C_GATE_HPP

#include <lua.hpp>

namespace lutok {


class state;


/// Gateway to the raw C state of Lua.
///
................................................................................

    static state connect(lua_State*);

    lua_State* c_state(void);
};


}  // namespace lutok

#endif  // !defined(LUTOK_C_GATE_HPP)







|







 







|


30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
..
62
63
64
65
66
67
68
69
70
71
/// Provides direct access to the C state of the Lua wrappers.

#if !defined(LUTOK_C_GATE_HPP)
#define LUTOK_C_GATE_HPP

#include <lua.hpp>

namespace xlua {


class state;


/// Gateway to the raw C state of Lua.
///
................................................................................

    static state connect(lua_State*);

    lua_State* c_state(void);
};


}  // namespace xlua

#endif  // !defined(LUTOK_C_GATE_HPP)

Changes to include/xlua/debug.hpp.

35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
..
81
82
83
84
85
86
87
88
89
90
#include <string>
#if defined(_LIBCPP_VERSION) || __cplusplus >= 201103L
#include <memory>
#else
#include <tr1/memory>
#endif

namespace lutok {


class state;


/// A model for the Lua debug state.
///
................................................................................
    int n_ups(void) const;
    int line_defined(void) const;
    int last_line_defined(void) const;
    std::string short_src(void) const;
};


}  // namespace lutok

#endif  // !defined(LUTOK_DEBUG_HPP)







|







 







|


35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
..
81
82
83
84
85
86
87
88
89
90
#include <string>
#if defined(_LIBCPP_VERSION) || __cplusplus >= 201103L
#include <memory>
#else
#include <tr1/memory>
#endif

namespace xlua {


class state;


/// A model for the Lua debug state.
///
................................................................................
    int n_ups(void) const;
    int line_defined(void) const;
    int last_line_defined(void) const;
    std::string short_src(void) const;
};


}  // namespace xlua

#endif  // !defined(LUTOK_DEBUG_HPP)

Changes to include/xlua/exceptions.hpp.

23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
..
73
74
75
76
77
78
79
80
81
82
83
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

/// \file exceptions.hpp
/// Exception types raised by lutok.

#if !defined(LUTOK_EXCEPTIONS_HPP)
#define LUTOK_EXCEPTIONS_HPP

#include <stdexcept>
#include <string>

namespace lutok {


class state;


/// Base exception for lua errors.
class error : public std::runtime_error {
................................................................................
    explicit file_not_found_error(const std::string&);
    virtual ~file_not_found_error(void) throw();

    const std::string& filename(void) const;
};


}  // namespace lutok


#endif  // !defined(LUTOK_EXCEPTIONS_HPP)







|







|







 







|



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
..
73
74
75
76
77
78
79
80
81
82
83
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

/// \file exceptions.hpp
/// Exception types raised by xlua.

#if !defined(LUTOK_EXCEPTIONS_HPP)
#define LUTOK_EXCEPTIONS_HPP

#include <stdexcept>
#include <string>

namespace xlua {


class state;


/// Base exception for lua errors.
class error : public std::runtime_error {
................................................................................
    explicit file_not_found_error(const std::string&);
    virtual ~file_not_found_error(void) throw();

    const std::string& filename(void) const;
};


}  // namespace xlua


#endif  // !defined(LUTOK_EXCEPTIONS_HPP)

Changes to include/xlua/operations.hpp.

34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55

#include <map>
#include <string>
#include <vector>

#include <xlua/state.hpp>

namespace lutok {


void create_module(state&, const std::string&,
                   const std::map< std::string, cxx_function >&);
unsigned int do_file(state&, const std::string&, const int, const int,
                     const int);
unsigned int do_string(state&, const std::string&, const int, const int,
                       const int);
void eval(state&, const std::string&, const int);


}  // namespace lutok

#endif  // !defined(LUTOK_OPERATIONS_HPP)







|











|


34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55

#include <map>
#include <string>
#include <vector>

#include <xlua/state.hpp>

namespace xlua {


void create_module(state&, const std::string&,
                   const std::map< std::string, cxx_function >&);
unsigned int do_file(state&, const std::string&, const int, const int,
                     const int);
unsigned int do_string(state&, const std::string&, const int, const int,
                       const int);
void eval(state&, const std::string&, const int);


}  // namespace xlua

#endif  // !defined(LUTOK_OPERATIONS_HPP)

Changes to include/xlua/stack_cleaner.hpp.

32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
..
84
85
86
87
88
89
90
91
92
93
#if !defined(LUTOK_STACK_CLEANER_HPP)
#define LUTOK_STACK_CLEANER_HPP

#include <memory>

#include <xlua/state.hpp>

namespace lutok {


/// A RAII model for values on the Lua stack.
///
/// At creation time, the object records the current depth of the Lua stack and,
/// during destruction, restores the recorded depth by popping as many stack
/// entries as required.  As a corollary, the stack can only grow during the
................................................................................
    stack_cleaner(state&);
    ~stack_cleaner(void);

    void forget(void);
};


}  // namespace lutok

#endif  // !defined(LUTOK_STACK_CLEANER_HPP)







|







 







|


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
..
84
85
86
87
88
89
90
91
92
93
#if !defined(LUTOK_STACK_CLEANER_HPP)
#define LUTOK_STACK_CLEANER_HPP

#include <memory>

#include <xlua/state.hpp>

namespace xlua {


/// A RAII model for values on the Lua stack.
///
/// At creation time, the object records the current depth of the Lua stack and,
/// during destruction, restores the recorded depth by popping as many stack
/// entries as required.  As a corollary, the stack can only grow during the
................................................................................
    stack_cleaner(state&);
    ~stack_cleaner(void);

    void forget(void);
};


}  // namespace xlua

#endif  // !defined(LUTOK_STACK_CLEANER_HPP)

Changes to include/xlua/state.hpp.

36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
...
136
137
138
139
140
141
142
143
144
145

#if defined(_LIBCPP_VERSION) || __cplusplus >= 201103L
#include <memory>
#else
#include <tr1/memory>
#endif

namespace lutok {


class debug;
class state;


/// The type of a C++ function that can be bound into Lua.
................................................................................
    long to_integer(const int);
    template< typename Type > Type* to_userdata(const int);
    std::string to_string(const int);
    int upvalue_index(const int);
};


}  // namespace lutok

#endif  // !defined(LUTOK_STATE_HPP)







|







 







|


36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
...
136
137
138
139
140
141
142
143
144
145

#if defined(_LIBCPP_VERSION) || __cplusplus >= 201103L
#include <memory>
#else
#include <tr1/memory>
#endif

namespace xlua {


class debug;
class state;


/// The type of a C++ function that can be bound into Lua.
................................................................................
    long to_integer(const int);
    template< typename Type > Type* to_userdata(const int);
    std::string to_string(const int);
    int upvalue_index(const int);
};


}  // namespace xlua

#endif  // !defined(LUTOK_STATE_HPP)

Changes to include/xlua/state.ipp.

27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
..
58
59
60
61
62
63
64
65
66
67
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#if !defined(LUTOK_STATE_IPP)
#define LUTOK_STATE_IPP

#include <xlua/state.hpp>

namespace lutok {


/// Wrapper around lua_newuserdata.
///
/// This allocates an object as big as the size of the provided Type.
///
/// \return The pointer to the allocated userdata object.
................................................................................
Type*
state::to_userdata(const int index)
{
    return static_cast< Type* >(to_userdata_voidp(index));
}


}  // namespace lutok

#endif  // !defined(LUTOK_STATE_IPP)







|







 







|


27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
..
58
59
60
61
62
63
64
65
66
67
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#if !defined(LUTOK_STATE_IPP)
#define LUTOK_STATE_IPP

#include <xlua/state.hpp>

namespace xlua {


/// Wrapper around lua_newuserdata.
///
/// This allocates an object as big as the size of the provided Type.
///
/// \return The pointer to the allocated userdata object.
................................................................................
Type*
state::to_userdata(const int index)
{
    return static_cast< Type* >(to_userdata_voidp(index));
}


}  // namespace xlua

#endif  // !defined(LUTOK_STATE_IPP)

Changes to include/xlua/test_utils.hpp.

37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
...
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
#   define LUTOK_TEST_UTILS_HPP
#else
#   error "test_utils.hpp can only be included once"
#endif

#include <atf-c++.hpp>

#include "c_gate.hpp"
#include "exceptions.hpp"
#include "state.hpp"


namespace {


/// Checks that a given expression raises a particular lutok::api_error.
///
/// We cannot make any assumptions regarding the error text provided by Lua, so
/// we resort to checking only which API function raised the error (because our
/// code is the one hardcoding these strings).
///
/// \param exp_api_function The name of the Lua C API function that causes the
///     error.
/// \param statement The statement to execute.
#define REQUIRE_API_ERROR(exp_api_function, statement) \
    do { \
        try { \
            statement; \
            ATF_FAIL("api_error not raised by " #statement); \
        } catch (const lutok::api_error& api_error) { \
            ATF_REQUIRE_EQ(exp_api_function, api_error.api_function()); \
        } \
    } while (0)


/// Gets the pointer to the internal lua_State of a state object.
///
/// This is pure syntactic sugar to simplify typing in the test cases.
///
/// \param state The Lua state.
///
/// \return The internal lua_State of the input Lua state.
static inline lua_State*
raw(lutok::state& state)
{
    return lutok::state_c_gate(state).c_state();
}


/// Ensures that the Lua stack maintains its original height upon exit.
///
/// Use an instance of this class to check that a piece of code does not have
/// side-effects on the Lua stack.
///
/// To be used within a test case only.
class stack_balance_checker {
    /// The Lua state.
    lutok::state& _state;

    /// Whether to install a sentinel on the stack for balance enforcement.
    bool _with_sentinel;

    /// The height of the stack on creation.
    unsigned int _old_count;

................................................................................
    /// Constructs a new stack balance checker.
    ///
    /// \param state_ The Lua state to validate.
    /// \param with_sentinel_ If true, insert a sentinel item into the stack and
    ///     validate upon exit that the item is still there.  This is an attempt
    ///     to ensure that already-existing items are not removed from the stack
    ///     by the code under test.
    stack_balance_checker(lutok::state& state_,
                          const bool with_sentinel_ = true) :
        _state(state_),
        _with_sentinel(with_sentinel_),
        _old_count(_state.get_top())
    {
        if (_with_sentinel)
            _state.push_integer(987654321);







|
|
|





|













|













|

|











|







 







|







37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
...
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
#   define LUTOK_TEST_UTILS_HPP
#else
#   error "test_utils.hpp can only be included once"
#endif

#include <atf-c++.hpp>

#include <xlua/c_gate.hpp>
#include <xlua/exceptions.hpp>
#include <xlua/state.hpp>


namespace {


/// Checks that a given expression raises a particular xlua::api_error.
///
/// We cannot make any assumptions regarding the error text provided by Lua, so
/// we resort to checking only which API function raised the error (because our
/// code is the one hardcoding these strings).
///
/// \param exp_api_function The name of the Lua C API function that causes the
///     error.
/// \param statement The statement to execute.
#define REQUIRE_API_ERROR(exp_api_function, statement) \
    do { \
        try { \
            statement; \
            ATF_FAIL("api_error not raised by " #statement); \
        } catch (const xlua::api_error& api_error) { \
            ATF_REQUIRE_EQ(exp_api_function, api_error.api_function()); \
        } \
    } while (0)


/// Gets the pointer to the internal lua_State of a state object.
///
/// This is pure syntactic sugar to simplify typing in the test cases.
///
/// \param state The Lua state.
///
/// \return The internal lua_State of the input Lua state.
static inline lua_State*
raw(xlua::state& state)
{
    return xlua::state_c_gate(state).c_state();
}


/// Ensures that the Lua stack maintains its original height upon exit.
///
/// Use an instance of this class to check that a piece of code does not have
/// side-effects on the Lua stack.
///
/// To be used within a test case only.
class stack_balance_checker {
    /// The Lua state.
    xlua::state& _state;

    /// Whether to install a sentinel on the stack for balance enforcement.
    bool _with_sentinel;

    /// The height of the stack on creation.
    unsigned int _old_count;

................................................................................
    /// Constructs a new stack balance checker.
    ///
    /// \param state_ The Lua state to validate.
    /// \param with_sentinel_ If true, insert a sentinel item into the stack and
    ///     validate upon exit that the item is still there.  This is an attempt
    ///     to ensure that already-existing items are not removed from the stack
    ///     by the code under test.
    stack_balance_checker(xlua::state& state_,
                          const bool with_sentinel_ = true) :
        _state(state_),
        _with_sentinel(with_sentinel_),
        _old_count(_state.get_top())
    {
        if (_with_sentinel)
            _state.push_integer(987654321);

Deleted operations.cpp.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
// Copyright 2011 Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
//   notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
//   notice, this list of conditions and the following disclaimer in the
//   documentation and/or other materials provided with the distribution.
// * Neither the name of Google Inc. nor the names of its contributors
//   may be used to endorse or promote products derived from this software
//   without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include <cassert>

#include <lua.hpp>

#include "exceptions.hpp"
#include "operations.hpp"
#include "stack_cleaner.hpp"
#include "state.hpp"


/// Creates a module: i.e. a table with a set of methods in it.
///
/// \param s The Lua state.
/// \param name The name of the module to create.
/// \param members The list of member functions to add to the module.
void
lutok::create_module(state& s, const std::string& name,
                     const std::map< std::string, cxx_function >& members)
{
    stack_cleaner cleaner(s);
    s.new_table();
    for (std::map< std::string, cxx_function >::const_iterator
         iter = members.begin(); iter != members.end(); iter++) {
        s.push_string((*iter).first);
        s.push_cxx_function((*iter).second);
        s.set_table(-3);
    }
    s.set_global(name);
}


/// Loads and processes a Lua file.
///
/// This is a replacement for luaL_dofile but with proper error reporting
/// and stack control.
///
/// \param s The Lua state.
/// \param file The file to load.
/// \param nargs The number of arguments on the stack to pass to the file.
/// \param nresults The number of results to expect; -1 for any.
/// \param errfunc If not 0, index of a function in the stack to act as an
///     error handler.
///
/// \return The number of results left on the stack.
///
/// \throw error If there is a problem processing the file.
unsigned int
lutok::do_file(state& s, const std::string& file, const int nargs,
               const int nresults, const int errfunc)
{
    assert(nresults >= -1);
    const int height = s.get_top() - nargs;

    try {
        s.load_file(file);
        if (nargs > 0)
            s.insert(-nargs - 1);
        s.pcall(nargs, nresults == -1 ? LUA_MULTRET : nresults,
                errfunc == 0 ? 0 : errfunc - 1);
    } catch (const lutok::api_error& e) {
        throw lutok::error("Failed to load Lua file '" + file + "': " +
                           e.what());
    }

    const int actual_results = s.get_top() - height;
    assert(nresults == -1 || actual_results == nresults);
    assert(actual_results >= 0);
    return static_cast< unsigned int >(actual_results);
}


/// Processes a Lua script.
///
/// This is a replacement for luaL_dostring but with proper error reporting
/// and stack control.
///
/// \param s The Lua state.
/// \param str The string to process.
/// \param nargs The number of arguments on the stack to pass to the chunk.
/// \param nresults The number of results to expect; -1 for any.
/// \param errfunc If not 0, index of a function in the stack to act as an
///     error handler.
///
/// \return The number of results left on the stack.
///
/// \throw error If there is a problem processing the string.
unsigned int
lutok::do_string(state& s, const std::string& str, const int nargs,
                 const int nresults, const int errfunc)
{
    assert(nresults >= -1);
    const int height = s.get_top() - nargs;

    try {
        s.load_string(str);
        if (nargs > 0)
            s.insert(-nargs - 1);
        s.pcall(nargs, nresults == -1 ? LUA_MULTRET : nresults,
                errfunc == 0 ? 0 : errfunc - 1);
    } catch (const lutok::api_error& e) {
        throw lutok::error("Failed to process Lua string '" + str + "': " +
                           e.what());
    }

    const int actual_results = s.get_top() - height;
    assert(nresults == -1 || actual_results == nresults);
    assert(actual_results >= 0);
    return static_cast< unsigned int >(actual_results);
}


/// Convenience function to evaluate a Lua expression.
///
/// \param s The Lua state.
/// \param expression The textual expression to evaluate.
/// \param nresults The number of results to leave on the stack.  Must be
///     positive.
///
/// \throw api_error If there is a problem evaluating the expression.
void
lutok::eval(state& s, const std::string& expression, const int nresults)
{
    assert(nresults > 0);
    do_string(s, "return " + expression, 0, nresults, 0);
}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


















































































































































































































































































































Added src/Makefile.











































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#
# Copyright (c) 2018 xjail.tiv.cc
#

LIB = xlua

WARNS = 4

SRCS = \
	c_gate.cpp \
	debug.cpp \
	exceptions.cpp \
	operations.cpp \
	stack_cleaner.cpp \
	state.cpp

CXXFLAGS += -I../include `pkgconf --cflags lua-5.3`
LDFLAGS += `pkgconf --libs lua-5.3`

.include "../compiler.config"
.include <bsd.lib.mk>

Added src/c_gate.cpp.





















































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// Copyright 2011 Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
//   notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
//   notice, this list of conditions and the following disclaimer in the
//   documentation and/or other materials provided with the distribution.
// * Neither the name of Google Inc. nor the names of its contributors
//   may be used to endorse or promote products derived from this software
//   without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include <xlua/c_gate.hpp>
#include <xlua/state.ipp>


/// Creates a new gateway to an existing C++ Lua state.
///
/// \param state_ The state to connect to.  This object must remain alive while
///     the newly-constructed state_c_gate is alive.
xlua::state_c_gate::state_c_gate(state& state_) :
    _state(state_)
{
}


/// Destructor.
///
/// Destroying this object has no implications on the life cycle of the Lua
/// state.  Only the corresponding state object controls when the Lua state is
/// closed.
xlua::state_c_gate::~state_c_gate(void)
{
}


/// Creates a C++ state for a C Lua state.
///
/// \warning The created state object does NOT own the C state.  You must take
/// care to properly destroy the input lua_State when you are done with it to
/// not leak resources.
///
/// \param raw_state The raw state to wrap temporarily.
///
/// \return The wrapped state without strong ownership on the input state.
xlua::state xlua::state_c_gate::connect(lua_State* raw_state)
{
    return state(static_cast< void* >(raw_state));
}


/// Returns the C native Lua state.
///
/// \return A native lua_State object holding the Lua C API state.
lua_State * xlua::state_c_gate::c_state(void)
{
    return static_cast< lua_State* >(_state.raw_state());
}

Added src/debug.cpp.









































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
// Copyright 2011 Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
//   notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
//   notice, this list of conditions and the following disclaimer in the
//   documentation and/or other materials provided with the distribution.
// * Neither the name of Google Inc. nor the names of its contributors
//   may be used to endorse or promote products derived from this software
//   without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include <cassert>

#include <lua.hpp>

#include <xlua/c_gate.hpp>
#include <xlua/debug.hpp>
#include <xlua/exceptions.hpp>
#include <xlua/state.ipp>


/// Internal implementation for xlua::debug.
struct xlua::debug::impl {
    /// The Lua internal debug state.
    lua_Debug lua_debug;
};


/// Constructor for an empty debug structure.
xlua::debug::debug(void) :
    _pimpl(new impl())
{
}


/// Destructor.
xlua::debug::~debug(void)
{
}


/// Wrapper around lua_getinfo.
///
/// \param s The Lua state.
/// \param what_ The second parameter to lua_getinfo.
///
/// \warning Terminates execution if there is not enough memory to manipulate
/// the Lua stack.
void xlua::debug::get_info(state& s, const std::string& what_)
{
    lua_State* raw_state = state_c_gate(s).c_state();

    if (lua_getinfo(raw_state, what_.c_str(), &_pimpl->lua_debug) == 0)
        throw xlua::api_error::from_stack(s, "lua_getinfo");
}


/// Wrapper around lua_getstack.
///
/// \param s The Lua state.
/// \param level The second parameter to lua_getstack.
void xlua::debug::get_stack(state& s, const int level)
{
    lua_State* raw_state = state_c_gate(s).c_state();

    lua_getstack(raw_state, level, &_pimpl->lua_debug);
}


/// Accessor for the 'event' field of lua_Debug.
///
/// \return Returns the 'event' field of the internal lua_Debug structure.
int xlua::debug::event(void) const
{
    return _pimpl->lua_debug.event;
}


/// Accessor for the 'name' field of lua_Debug.
///
/// \return Returns the 'name' field of the internal lua_Debug structure.
std::string xlua::debug::name(void) const
{
    assert(_pimpl->lua_debug.name != NULL);
    return _pimpl->lua_debug.name;
}


/// Accessor for the 'namewhat' field of lua_Debug.
///
/// \return Returns the 'namewhat' field of the internal lua_Debug structure.
std::string xlua::debug::name_what(void) const
{
    assert(_pimpl->lua_debug.namewhat != NULL);
    return _pimpl->lua_debug.namewhat;
}


/// Accessor for the 'what' field of lua_Debug.
///
/// \return Returns the 'what' field of the internal lua_Debug structure.
std::string xlua::debug::what(void) const
{
    assert(_pimpl->lua_debug.what != NULL);
    return _pimpl->lua_debug.what;
}


/// Accessor for the 'source' field of lua_Debug.
///
/// \return Returns the 'source' field of the internal lua_Debug structure.
std::string xlua::debug::source(void) const
{
    assert(_pimpl->lua_debug.source != NULL);
    return _pimpl->lua_debug.source;
}


/// Accessor for the 'currentline' field of lua_Debug.
///
/// \return Returns the 'currentline' field of the internal lua_Debug structure.
int xlua::debug::current_line(void) const
{
    return _pimpl->lua_debug.currentline;
}


/// Accessor for the 'nups' field of lua_Debug.
///
/// \return Returns the 'nups' field of the internal lua_Debug structure.
int xlua::debug::n_ups(void) const
{
    return _pimpl->lua_debug.nups;
}


/// Accessor for the 'linedefined' field of lua_Debug.
///
/// \return Returns the 'linedefined' field of the internal lua_Debug structure.
int xlua::debug::line_defined(void) const
{
    return _pimpl->lua_debug.linedefined;
}


/// Accessor for the 'lastlinedefined' field of lua_Debug.
///
/// \return Returns the 'lastlinedefined' field of the internal lua_Debug
/// structure.
int xlua::debug::last_line_defined(void) const
{
    return _pimpl->lua_debug.lastlinedefined;
}


/// Accessor for the 'short_src' field of lua_Debug.
///
/// \return Returns the 'short_src' field of the internal lua_Debug structure.
std::string xlua::debug::short_src(void) const
{
    assert(_pimpl->lua_debug.short_src != NULL);
    return _pimpl->lua_debug.short_src;
}

Added src/exceptions.cpp.



















































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
// Copyright 2011 Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
//   notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
//   notice, this list of conditions and the following disclaimer in the
//   documentation and/or other materials provided with the distribution.
// * Neither the name of Google Inc. nor the names of its contributors
//   may be used to endorse or promote products derived from this software
//   without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include <cassert>

#include <lua.hpp>

#include <xlua/c_gate.hpp>
#include <xlua/exceptions.hpp>
#include <xlua/state.ipp>


/// Constructs a new error with a plain-text message.
///
/// \param message The plain-text error message.
xlua::error::error(const std::string& message) :
    std::runtime_error(message)
{
}


/// Destructor for the error.
xlua::error::~error(void) throw()
{
}


/// Constructs a new error.
///
/// \param api_function_ The name of the API function that caused the error.
/// \param message The plain-text error message provided by Lua.
xlua::api_error::api_error(const std::string& api_function_,
                            const std::string& message) :
    error(message),
    _api_function(api_function_)
{
}


/// Destructor for the error.
xlua::api_error::~api_error(void) throw()
{
}


/// Constructs a new api_error with the message on the top of the Lua stack.
///
/// \pre There is an error message on the top of the stack.
/// \post The error message is popped from the stack.
///
/// \param state_ The Lua state.
/// \param api_function_ The name of the Lua API function that caused the error.
///
/// \return A new api_error with the popped message.
xlua::api_error xlua::api_error::from_stack(state& state_,
		const std::string& api_function_) {
    lua_State* raw_state = xlua::state_c_gate(state_).c_state();

    assert(lua_isstring(raw_state, -1));
    const std::string message = lua_tostring(raw_state, -1);
    lua_pop(raw_state, 1);
    return xlua::api_error(api_function_, message);
}


/// Gets the name of the Lua API function that caused this error.
///
/// \return The name of the function.
const std::string& xlua::api_error::api_function(void) const {
    return _api_function;
}
 

/// Constructs a new error.
///
/// \param filename_ The file that count not be found.
xlua::file_not_found_error::file_not_found_error(
    const std::string& filename_) :
    error("File '" + filename_ + "' not found"),
    _filename(filename_)
{
}


/// Destructor for the error.
xlua::file_not_found_error::~file_not_found_error(void) throw()
{
}


/// Gets the name of the file that could not be found.
///
/// \return The name of the file.
const std::string& xlua::file_not_found_error::filename(void) const {
    return _filename;
}

Added src/operations.cpp.

















































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
// Copyright 2011 Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
//   notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
//   notice, this list of conditions and the following disclaimer in the
//   documentation and/or other materials provided with the distribution.
// * Neither the name of Google Inc. nor the names of its contributors
//   may be used to endorse or promote products derived from this software
//   without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include <cassert>

#include <lua.hpp>

#include <xlua/exceptions.hpp>
#include <xlua/operations.hpp>
#include <xlua/stack_cleaner.hpp>
#include <xlua/state.hpp>


/// Creates a module: i.e. a table with a set of methods in it.
///
/// \param s The Lua state.
/// \param name The name of the module to create.
/// \param members The list of member functions to add to the module.
void xlua::create_module(state& s, const std::string& name,
                     const std::map< std::string, cxx_function >& members)
{
    stack_cleaner cleaner(s);
    s.new_table();
    for (std::map< std::string, cxx_function >::const_iterator
         iter = members.begin(); iter != members.end(); iter++) {
        s.push_string((*iter).first);
        s.push_cxx_function((*iter).second);
        s.set_table(-3);
    }
    s.set_global(name);
}


/// Loads and processes a Lua file.
///
/// This is a replacement for luaL_dofile but with proper error reporting
/// and stack control.
///
/// \param s The Lua state.
/// \param file The file to load.
/// \param nargs The number of arguments on the stack to pass to the file.
/// \param nresults The number of results to expect; -1 for any.
/// \param errfunc If not 0, index of a function in the stack to act as an
///     error handler.
///
/// \return The number of results left on the stack.
///
/// \throw error If there is a problem processing the file.
unsigned int xlua::do_file(state& s, 
				const std::string& file, const int nargs,
				const int nresults, const int errfunc)
{
    assert(nresults >= -1);
    const int height = s.get_top() - nargs;

    try {
        s.load_file(file);
        if (nargs > 0)
            s.insert(-nargs - 1);
        s.pcall(nargs, nresults == -1 ? LUA_MULTRET : nresults,
                errfunc == 0 ? 0 : errfunc - 1);
    } catch (const xlua::api_error& e) {
        throw xlua::error("Failed to load Lua file '" + file + "': " +
                           e.what());
    }

    const int actual_results = s.get_top() - height;
    assert(nresults == -1 || actual_results == nresults);
    assert(actual_results >= 0);
    return static_cast< unsigned int >(actual_results);
}


/// Processes a Lua script.
///
/// This is a replacement for luaL_dostring but with proper error reporting
/// and stack control.
///
/// \param s The Lua state.
/// \param str The string to process.
/// \param nargs The number of arguments on the stack to pass to the chunk.
/// \param nresults The number of results to expect; -1 for any.
/// \param errfunc If not 0, index of a function in the stack to act as an
///     error handler.
///
/// \return The number of results left on the stack.
///
/// \throw error If there is a problem processing the string.
unsigned int xlua::do_string(state& s, 
				const std::string& str, const int nargs,
				const int nresults, const int errfunc)
{
    assert(nresults >= -1);
    const int height = s.get_top() - nargs;

    try {
        s.load_string(str);
        if (nargs > 0)
            s.insert(-nargs - 1);
        s.pcall(nargs, nresults == -1 ? LUA_MULTRET : nresults,
                errfunc == 0 ? 0 : errfunc - 1);
    } catch (const xlua::api_error& e) {
        throw xlua::error("Failed to process Lua string '" + str + "': " +
                           e.what());
    }

    const int actual_results = s.get_top() - height;
    assert(nresults == -1 || actual_results == nresults);
    assert(actual_results >= 0);
    return static_cast< unsigned int >(actual_results);
}


/// Convenience function to evaluate a Lua expression.
///
/// \param s The Lua state.
/// \param expression The textual expression to evaluate.
/// \param nresults The number of results to leave on the stack.  Must be
///     positive.
///
/// \throw api_error If there is a problem evaluating the expression.
void
xlua::eval(state& s, const std::string& expression, const int nresults)
{
    assert(nresults > 0);
    do_string(s, "return " + expression, 0, nresults, 0);
}

Added src/stack_cleaner.cpp.



















































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// Copyright 2011 Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
//   notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
//   notice, this list of conditions and the following disclaimer in the
//   documentation and/or other materials provided with the distribution.
// * Neither the name of Google Inc. nor the names of its contributors
//   may be used to endorse or promote products derived from this software
//   without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include <cassert>
#include <cstring>

#include <xlua/stack_cleaner.hpp>
#include <xlua/state.ipp>


/// Internal implementation for xlua::stack_cleaner.
struct xlua::stack_cleaner::impl {
    /// Reference to the Lua state this stack_cleaner refers to.
    state& state_ref;

    /// The depth of the Lua stack to be restored.
    unsigned int original_depth;

    /// Constructor.
    ///
    /// \param state_ref_ Reference to the Lua state.
    /// \param original_depth_ The depth of the Lua stack.
    impl(state& state_ref_, const unsigned int original_depth_) :
        state_ref(state_ref_),
        original_depth(original_depth_)
    {
    }
};


/// Creates a new stack cleaner.
///
/// This gathers the current height of the stack so that extra elements can be
/// popped during destruction.
///
/// \param state_ The Lua state.
xlua::stack_cleaner::stack_cleaner(state& state_) :
    _pimpl(new impl(state_, state_.get_top()))
{
}


/// Pops any values from the stack not known at construction time.
///
/// \pre The current height of the stack must be equal or greater to the height
/// of the stack when this object was instantiated.
xlua::stack_cleaner::~stack_cleaner(void)
{
    const unsigned int current_depth = _pimpl->state_ref.get_top();
    assert(current_depth >= _pimpl->original_depth);
    const unsigned int diff = current_depth - _pimpl->original_depth;
    if (diff > 0)
        _pimpl->state_ref.pop(diff);
}


/// Forgets about any elements currently in the stack.
///
/// This allows a function to return values on the stack because all the
/// elements that are currently in the stack will not be touched during
/// destruction when the function is called.
void xlua::stack_cleaner::forget(void) {
    _pimpl->original_depth = _pimpl->state_ref.get_top();
}

Added src/state.cpp.

































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
// Copyright 2011 Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
//   notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
//   notice, this list of conditions and the following disclaimer in the
//   documentation and/or other materials provided with the distribution.
// * Neither the name of Google Inc. nor the names of its contributors
//   may be used to endorse or promote products derived from this software
//   without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

extern "C" {
#include <unistd.h>
}

#include <cassert>
#include <cstring>

#include <xlua/c_gate.hpp>
#include <xlua/exceptions.hpp>
#include <xlua/state.ipp>


namespace {


/// Wrapper around lua_getglobal to run in a protected environment.
///
/// \pre stack(-1) is the name of the global to get.
/// \post stack(-1) is the value of the global.
///
/// \param state The Lua C API state.
///
/// \return The number of return values pushed onto the stack.
static int
protected_getglobal(lua_State* state)
{
    lua_getglobal(state, lua_tostring(state, -1));
    return 1;
}


/// Wrapper around lua_gettable to run in a protected environment.
///
/// \pre stack(-2) is the table to get the element from.
/// \pre stack(-1) is the table index.
/// \post stack(-1) is the value of stack(-2)[stack(-1)].
///
/// \param state The Lua C API state.
///
/// \return The number of return values pushed onto the stack.
static int
protected_gettable(lua_State* state)
{
    lua_gettable(state, -2);
    return 1;
}


/// Wrapper around lua_next to run in a protected environment.
///
/// \pre stack(-2) is the table to get the next element from.
/// \pre stack(-1) is the last processed key.
/// \post stack(-1) is the value of next(stack(-2), stack(-1)).
///
/// \param state The Lua C API state.
///
/// \return The number of return values pushed onto the stack.
static int
protected_next(lua_State* state)
{
    const int more = lua_next(state, -2) != 0;
    lua_pushboolean(state, more);
    return more ? 3 : 1;
}


/// Wrapper around lua_setglobal to run in a protected environment.
///
/// \pre stack(-2) is the name of the global to set.
/// \pre stack(-1) is the value to set the global to.
///
/// \param state The Lua C API state.
///
/// \return The number of return values pushed onto the stack.
static int
protected_setglobal(lua_State* state)
{
    lua_setglobal(state, lua_tostring(state, -2));
    return 0;
}


/// Wrapper around lua_settable to run in a protected environment.
///
/// \pre stack(-3) is the table to set the element into.
/// \pre stack(-2) is the table index.
/// \pre stack(-1) is the value to set.
///
/// \param state The Lua C API state.
///
/// \return The number of return values pushed onto the stack.
static int
protected_settable(lua_State* state)
{
    lua_settable(state, -3);
    return 0;
}


/// Calls a C++ Lua function from a C calling environment.
///
/// Any errors reported by the C++ function are caught and reported to the
/// caller as Lua errors.
///
/// \param function The C++ function to call.
/// \param raw_state The raw Lua state.
///
/// \return The number of return values pushed onto the Lua stack by the
/// function.
static int
call_cxx_function_from_c(xlua::cxx_function function,
                         lua_State* raw_state) throw()
{
    char error_buf[1024];

    try {
        xlua::state state = xlua::state_c_gate::connect(raw_state);
        return function(state);
    } catch (const std::exception& e) {
        std::strncpy(error_buf, e.what(), sizeof(error_buf));
    } catch (...) {
        std::strncpy(error_buf, "Unhandled exception in Lua C++ hook",
                     sizeof(error_buf));
    }
    error_buf[sizeof(error_buf) - 1] = '\0';
    // We raise the Lua error from outside the try/catch context and we use
    // a stack-based buffer to hold the message to ensure that we do not leak
    // any C++ objects (and, as a likely result, memory) when Lua performs its
    // longjmp.
    return luaL_error(raw_state, "%s", error_buf);
}


/// Lua glue to call a C++ closure.
///
/// This Lua binding is actually a closure that we have constructed from the
/// state.push_cxx_closure() method.  The closure contains the same upvalues
/// provided by the user plus an extra upvalue that contains the address of the
/// C++ function we have to call.  All we do here is safely delegate the
/// execution to the wrapped C++ closure.
///
/// \param raw_state The Lua C API state.
///
/// \return The number of return values of the called closure.
static int
cxx_closure_trampoline(lua_State* raw_state)
{
    xlua::state state = xlua::state_c_gate::connect(raw_state);

    int nupvalues;
    {
        lua_Debug debug;
        lua_getstack(raw_state, 0, &debug);
        lua_getinfo(raw_state, "u", &debug);
        nupvalues = debug.nups;
    }

    xlua::cxx_function* function = state.to_userdata<xlua::cxx_function>(
        state.upvalue_index(nupvalues));
    return call_cxx_function_from_c(*function, raw_state);
}


/// Lua glue to call a C++ function.
///
/// This Lua binding is actually a closure that we have constructed from the
/// state.push_cxx_function() method.  The closure has a single upvalue that
/// contains the address of the C++ function we have to call.  All we do here is
/// safely delegate the execution to the wrapped C++ function.
///
/// \param raw_state The Lua C API state.
///
/// \return The number of return values of the called function.
static int
cxx_function_trampoline(lua_State* raw_state)
{
    xlua::state state = xlua::state_c_gate::connect(raw_state);
    xlua::cxx_function* function = state.to_userdata<xlua::cxx_function>(
        state.upvalue_index(1));
    return call_cxx_function_from_c(*function, raw_state);
}


}  // anonymous namespace


const int xlua::registry_index = LUA_REGISTRYINDEX;


/// Internal implementation for xlua::state.
struct xlua::state::impl {
    /// The Lua internal state.
    lua_State* lua_state;

    /// Whether we own the state or not (to decide if we close it).
    bool owned;

    /// Constructor.
    ///
    /// \param lua_ The Lua internal state.
    /// \param owned_ Whether we own the state or not.
    impl(lua_State* lua_, bool owned_) :
        lua_state(lua_),
        owned(owned_)
    {
    }
};


/// Initializes the Lua state.
///
/// You must share the same state object alongside the lifetime of your Lua
/// session.  As soon as the object is destroyed, the session is terminated.
xlua::state::state(void)
{
    lua_State* lua = luaL_newstate();
    if (lua == NULL)
        throw xlua::error("lua open failed");
    _pimpl.reset(new impl(lua, true));
}


/// Initializes the Lua state from an existing raw state.
///
/// Instances constructed using this method do NOT own the raw state.  This
/// means that, on exit, the state will not be destroyed.
///
/// \param raw_state_ The raw Lua state to wrap.
xlua::state::state(void* raw_state_) :
    _pimpl(new impl(reinterpret_cast< lua_State* >(raw_state_), false))
{
}


/// Destructor for the Lua state.
///
/// Closes the session unless it has already been closed by calling the
/// close() method.  It is recommended to explicitly close the session in the
/// code.
xlua::state::~state(void)
{
    if (_pimpl->owned && _pimpl->lua_state != NULL)
        close();
}


/// Terminates this Lua session.
///
/// It is recommended to call this instead of relying on the destructor to do
/// the cleanup, but it is not a requirement to use close().
///
/// \pre close() has not yet been called.
/// \pre The Lua stack is empty.  This is not truly necessary but ensures that
///     our code is consistent and clears the stack explicitly.
void xlua::state::close(void)
{
    assert(_pimpl->lua_state != NULL);
    assert(lua_gettop(_pimpl->lua_state) == 0);
    lua_close(_pimpl->lua_state);
    _pimpl->lua_state = NULL;
}


/// Wrapper around lua_getglobal.
///
/// \param name The second parameter to lua_getglobal.
///
/// \throw api_error If lua_getglobal fails.
///
/// \warning Terminates execution if there is not enough memory to manipulate
/// the Lua stack.
void
xlua::state::get_global(const std::string& name)
{
    lua_pushcfunction(_pimpl->lua_state, protected_getglobal);
    lua_pushstring(_pimpl->lua_state, name.c_str());
    if (lua_pcall(_pimpl->lua_state, 1, 1, 0) != 0)
        throw xlua::api_error::from_stack(*this, "lua_getglobal");
}


/// Pushes a reference to the global table onto the stack.
///
/// This is a wrapper around the incompatible differences between Lua 5.1 and
/// 5.2 to access to the globals table.
///
/// \post state(-1) Contains the reference to the globals table.
void
xlua::state::get_global_table(void)
{
#if LUA_VERSION_NUM >= 502
    lua_pushvalue(_pimpl->lua_state, registry_index);
    lua_pushinteger(_pimpl->lua_state, LUA_RIDX_GLOBALS);
    lua_gettable(_pimpl->lua_state, -2);
    lua_remove(_pimpl->lua_state, -2);
#else
    lua_pushvalue(_pimpl->lua_state, LUA_GLOBALSINDEX);
#endif
}


/// Wrapper around luaL_getmetafield.
///
/// \param index The second parameter to luaL_getmetafield.
/// \param name The third parameter to luaL_getmetafield.
///
/// \return The return value of luaL_getmetafield.
///
/// \warning Terminates execution if there is not enough memory to manipulate
/// the Lua stack.
bool xlua::state::get_metafield(const int index, const std::string& name)
{
    return luaL_getmetafield(_pimpl->lua_state, index, name.c_str()) != 0;
}


/// Wrapper around lua_getmetatable.
///
/// \param index The second parameter to lua_getmetatable.
///
/// \return The return value of lua_getmetatable.
bool xlua::state::get_metatable(const int index)
{
    return lua_getmetatable(_pimpl->lua_state, index) != 0;
}


/// Wrapper around lua_gettable.
///
/// \param index The second parameter to lua_gettable.
///
/// \throw api_error If lua_gettable fails.
///
/// \warning Terminates execution if there is not enough memory to manipulate
/// the Lua stack.
void xlua::state::get_table(const int index)
{
    assert(lua_gettop(_pimpl->lua_state) >= 2);
    lua_pushcfunction(_pimpl->lua_state, protected_gettable);
    lua_pushvalue(_pimpl->lua_state, index < 0 ? index - 1 : index);
    lua_pushvalue(_pimpl->lua_state, -3);
    if (lua_pcall(_pimpl->lua_state, 2, 1, 0) != 0)
        throw xlua::api_error::from_stack(*this, "lua_gettable");
    lua_remove(_pimpl->lua_state, -2);
}


/// Wrapper around lua_gettop.
///
/// \return The return value of lua_gettop.
int xlua::state::get_top(void)
{
    return lua_gettop(_pimpl->lua_state);
}


/// Wrapper around lua_insert.
///
/// \param index The second parameter to lua_insert.
void xlua::state::insert(const int index)
{
    lua_insert(_pimpl->lua_state, index);
}


/// Wrapper around lua_isboolean.
///
/// \param index The second parameter to lua_isboolean.
///
/// \return The return value of lua_isboolean.
bool xlua::state::is_boolean(const int index)
{
    return lua_isboolean(_pimpl->lua_state, index);
}


/// Wrapper around lua_isfunction.
///
/// \param index The second parameter to lua_isfunction.
///
/// \return The return value of lua_isfunction.
bool xlua::state::is_function(const int index)
{
    return lua_isfunction(_pimpl->lua_state, index);
}


/// Wrapper around lua_isnil.
///
/// \param index The second parameter to lua_isnil.
///
/// \return The return value of lua_isnil.
bool xlua::state::is_nil(const int index)
{
    return lua_isnil(_pimpl->lua_state, index);
}


/// Wrapper around lua_isnumber.
///
/// \param index The second parameter to lua_isnumber.
///
/// \return The return value of lua_isnumber.
bool
xlua::state::is_number(const int index)
{
    return lua_isnumber(_pimpl->lua_state, index);
}


/// Wrapper around lua_isstring.
///
/// \param index The second parameter to lua_isstring.
///
/// \return The return value of lua_isstring.
bool xlua::state::is_string(const int index)
{
    return lua_isstring(_pimpl->lua_state, index);
}


/// Wrapper around lua_istable.
///
/// \param index The second parameter to lua_istable.
///
/// \return The return value of lua_istable.
bool xlua::state::is_table(const int index)
{
    return lua_istable(_pimpl->lua_state, index);
}


/// Wrapper around lua_isuserdata.
///
/// \param index The second parameter to lua_isuserdata.
///
/// \return The return value of lua_isuserdata.
bool xlua::state::is_userdata(const int index)
{
    return lua_isuserdata(_pimpl->lua_state, index);
}


/// Wrapper around luaL_loadfile.
///
/// \param file The second parameter to luaL_loadfile.
///
/// \throw api_error If luaL_loadfile returns an error.
/// \throw file_not_found_error If the file cannot be accessed.
///
/// \warning Terminates execution if there is not enough memory.
void xlua::state::load_file(const std::string& file)
{
    if (::access(file.c_str(), R_OK) == -1)
        throw xlua::file_not_found_error(file);
    if (luaL_loadfile(_pimpl->lua_state, file.c_str()) != 0)
        throw xlua::api_error::from_stack(*this, "luaL_loadfile");
}


/// Wrapper around luaL_loadstring.
///
/// \param str The second parameter to luaL_loadstring.
///
/// \throw api_error If luaL_loadstring returns an error.
///
/// \warning Terminates execution if there is not enough memory.
void xlua::state::load_string(const std::string& str)
{
    if (luaL_loadstring(_pimpl->lua_state, str.c_str()) != 0)
        throw xlua::api_error::from_stack(*this, "luaL_loadstring");
}


/// Wrapper around lua_newtable.
///
/// \warning Terminates execution if there is not enough memory.
void xlua::state::new_table(void)
{
    lua_newtable(_pimpl->lua_state);
}


/// Wrapper around lua_newuserdata.
///
/// This is internal.  The public type-safe interface of this method should be
/// used instead.
///
/// \param size The second parameter to lua_newuserdata.
///
/// \return The return value of lua_newuserdata.
///
/// \warning Terminates execution if there is not enough memory.
void* xlua::state::new_userdata_voidp(const size_t size)
{
    return lua_newuserdata(_pimpl->lua_state, size);
}


/// Wrapper around lua_next.
///
/// \param index The second parameter to lua_next.
///
/// \return True if there are more elements to process; false otherwise.
///
/// \warning Terminates execution if there is not enough memory.
bool xlua::state::next(const int index)
{
    assert(lua_istable(_pimpl->lua_state, index));
    assert(lua_gettop(_pimpl->lua_state) >= 1);
    lua_pushcfunction(_pimpl->lua_state, protected_next);
    lua_pushvalue(_pimpl->lua_state, index < 0 ? index - 1 : index);
    lua_pushvalue(_pimpl->lua_state, -3);
    if (lua_pcall(_pimpl->lua_state, 2, LUA_MULTRET, 0) != 0)
        throw xlua::api_error::from_stack(*this, "lua_next");
    const bool more = lua_toboolean(_pimpl->lua_state, -1);
    lua_pop(_pimpl->lua_state, 1);
    if (more)
        lua_remove(_pimpl->lua_state, -3);
    else
        lua_pop(_pimpl->lua_state, 1);
    return more;
}


/// Wrapper around luaL_openlibs.
///
/// \throw api_error If luaL_openlibs fails.
///
/// \warning Terminates execution if there is not enough memory.
void xlua::state::open_all(void)
{
    luaL_openlibs(_pimpl->lua_state);
}


/// Wrapper around luaopen_base.
///
/// \throw api_error If luaopen_base fails.
///
/// \warning Terminates execution if there is not enough memory.
void xlua::state::open_base(void)
{
    lua_pushcfunction(_pimpl->lua_state, luaopen_base);
    if (lua_pcall(_pimpl->lua_state, 0, 0, 0) != 0)
        throw xlua::api_error::from_stack(*this, "luaopen_base");
}


/// Wrapper around luaopen_string.
///
/// \throw api_error If luaopen_string fails.
///
/// \warning Terminates execution if there is not enough memory.
void xlua::state::open_string(void)
{
#if LUA_VERSION_NUM >= 502
    luaL_requiref(_pimpl->lua_state, LUA_STRLIBNAME, luaopen_string, 1);
    lua_pop(_pimpl->lua_state, 1);
#else
    lua_pushcfunction(_pimpl->lua_state, luaopen_string);
    if (lua_pcall(_pimpl->lua_state, 0, 0, 0) != 0)
        throw xlua::api_error::from_stack(*this, "luaopen_string");
#endif
}


/// Wrapper around luaopen_table.
///
/// \throw api_error If luaopen_table fails.
///
/// \warning Terminates execution if there is not enough memory.
void xlua::state::open_table(void)
{
#if LUA_VERSION_NUM >= 502
    luaL_requiref(_pimpl->lua_state, LUA_TABLIBNAME, luaopen_table, 1);
    lua_pop(_pimpl->lua_state, 1);
#else
    lua_pushcfunction(_pimpl->lua_state, luaopen_table);
    if (lua_pcall(_pimpl->lua_state, 0, 0, 0) != 0)
        throw xlua::api_error::from_stack(*this, "luaopen_table");
#endif
}


/// Wrapper around lua_pcall.
///
/// \param nargs The second parameter to lua_pcall.
/// \param nresults The third parameter to lua_pcall.
/// \param errfunc The fourth parameter to lua_pcall.
///
/// \throw api_error If lua_pcall returns an error.
void xlua::state::pcall(const int nargs, const int nresults, const int errfunc)
{
    if (lua_pcall(_pimpl->lua_state, nargs, nresults, errfunc) != 0)
        throw xlua::api_error::from_stack(*this, "lua_pcall");
}


/// Wrapper around lua_pop.
///
/// \param count The second parameter to lua_pop.
void xlua::state::pop(const int count)
{
    assert(count <= lua_gettop(_pimpl->lua_state));
    lua_pop(_pimpl->lua_state, count);
    assert(lua_gettop(_pimpl->lua_state) >= 0);
}


/// Wrapper around lua_pushboolean.
///
/// \param value The second parameter to lua_pushboolean.
void xlua::state::push_boolean(const bool value)
{
    lua_pushboolean(_pimpl->lua_state, value ? 1 : 0);
}


/// Wrapper around lua_pushcclosure.
///
/// This is not a pure wrapper around lua_pushcclosure because this has to do
/// extra magic to allow passing C++ functions instead of plain C functions.
///
/// \param function The C++ function to be pushed as a closure.
/// \param nvalues The number of upvalues that the function receives.
void xlua::state::push_cxx_closure(cxx_function function, const int nvalues)
{
    cxx_function *data = static_cast< cxx_function* >(
        lua_newuserdata(_pimpl->lua_state, sizeof(cxx_function)));
    *data = function;
    lua_pushcclosure(_pimpl->lua_state, cxx_closure_trampoline, nvalues + 1);
}


/// Wrapper around lua_pushcfunction.
///
/// This is not a pure wrapper around lua_pushcfunction because this has to do
/// extra magic to allow passing C++ functions instead of plain C functions.
///
/// \param function The C++ function to be pushed.
void xlua::state::push_cxx_function(cxx_function function)
{
    cxx_function *data = static_cast< cxx_function* >(
        lua_newuserdata(_pimpl->lua_state, sizeof(cxx_function)));
    *data = function;
    lua_pushcclosure(_pimpl->lua_state, cxx_function_trampoline, 1);
}


/// Wrapper around lua_pushinteger.
///
/// \param value The second parameter to lua_pushinteger.
void xlua::state::push_integer(const int value)
{
    lua_pushinteger(_pimpl->lua_state, value);
}


/// Wrapper around lua_pushnil.
void xlua::state::push_nil(void)
{
    lua_pushnil(_pimpl->lua_state);
}


/// Wrapper around lua_pushstring.
///
/// \param str The second parameter to lua_pushstring.
///
/// \warning Terminates execution if there is not enough memory.
void xlua::state::push_string(const std::string& str)
{
    lua_pushstring(_pimpl->lua_state, str.c_str());
}


/// Wrapper around lua_pushvalue.
///
/// \param index The second parameter to lua_pushvalue.
void xlua::state::push_value(const int index)
{
    lua_pushvalue(_pimpl->lua_state, index);
}


/// Wrapper around lua_rawget.
///
/// \param index The second parameter to lua_rawget.
void xlua::state::raw_get(const int index)
{
    lua_rawget(_pimpl->lua_state, index);
}


/// Wrapper around lua_rawset.
///
/// \param index The second parameter to lua_rawset.
///
/// \warning Terminates execution if there is not enough memory to manipulate
/// the Lua stack.
void xlua::state::raw_set(const int index)
{
    lua_rawset(_pimpl->lua_state, index);
}


/// Wrapper around lua_setglobal.
///
/// \param name The second parameter to lua_setglobal.
///
/// \throw api_error If lua_setglobal fails.
///
/// \warning Terminates execution if there is not enough memory to manipulate
/// the Lua stack.
void xlua::state::set_global(const std::string& name)
{
    lua_pushcfunction(_pimpl->lua_state, protected_setglobal);
    lua_pushstring(_pimpl->lua_state, name.c_str());
    lua_pushvalue(_pimpl->lua_state, -3);
    if (lua_pcall(_pimpl->lua_state, 2, 0, 0) != 0)
        throw xlua::api_error::from_stack(*this, "lua_setglobal");
    lua_pop(_pimpl->lua_state, 1);
}


/// Wrapper around lua_setmetatable.
///
/// \param index The second parameter to lua_setmetatable.
void xlua::state::set_metatable(const int index)
{
    lua_setmetatable(_pimpl->lua_state, index);
}


/// Wrapper around lua_settable.
///
/// \param index The second parameter to lua_settable.
///
/// \throw api_error If lua_settable fails.
///
/// \warning Terminates execution if there is not enough memory to manipulate
/// the Lua stack.
void xlua::state::set_table(const int index)
{
    lua_pushcfunction(_pimpl->lua_state, protected_settable);
    lua_pushvalue(_pimpl->lua_state, index < 0 ? index - 1 : index);
    lua_pushvalue(_pimpl->lua_state, -4);
    lua_pushvalue(_pimpl->lua_state, -4);
    if (lua_pcall(_pimpl->lua_state, 3, 0, 0) != 0)
        throw xlua::api_error::from_stack(*this, "lua_settable");
    lua_pop(_pimpl->lua_state, 2);
}


/// Wrapper around lua_toboolean.
///
/// \param index The second parameter to lua_toboolean.
///
/// \return The return value of lua_toboolean.
bool xlua::state::to_boolean(const int index)
{
    assert(is_boolean(index));
    return lua_toboolean(_pimpl->lua_state, index);
}


/// Wrapper around lua_tointeger.
///
/// \param index The second parameter to lua_tointeger.
///
/// \return The return value of lua_tointeger.
long xlua::state::to_integer(const int index)
{
    assert(is_number(index));
    return lua_tointeger(_pimpl->lua_state, index);
}


/// Wrapper around lua_touserdata.
///
/// This is internal.  The public type-safe interface of this method should be
/// used instead.
///
/// \param index The second parameter to lua_touserdata.
///
/// \return The return value of lua_touserdata.
///
/// \warning Terminates execution if there is not enough memory.
void* xlua::state::to_userdata_voidp(const int index)
{
    return lua_touserdata(_pimpl->lua_state, index);
}



/// Wrapper around lua_tostring.
///
/// \param index The second parameter to lua_tostring.
///
/// \return The return value of lua_tostring.
///
/// \warning Terminates execution if there is not enough memory.
std::string xlua::state::to_string(const int index)
{
    assert(is_string(index));
    const char *raw_string = lua_tostring(_pimpl->lua_state, index);
    // Note that the creation of a string object below (explicit for clarity)
    // implies that the raw string is duplicated and, henceforth, the string is
    // safe even if the corresponding element is popped from the Lua stack.
    return std::string(raw_string);
}


/// Wrapper around lua_upvalueindex.
///
/// \param index The first parameter to lua_upvalueindex.
///
/// \return The return value of lua_upvalueindex.
int
xlua::state::upvalue_index(const int index)
{
    return lua_upvalueindex(index);
}


/// Gets the internal lua_State object.
///
/// \return The raw Lua state.  This is returned as a void pointer to prevent
/// including the lua.hpp header file from our public interface.  The only way
/// to call this method is by using the c_gate module, and c_gate takes care of
/// casting this object to the appropriate type.
void* xlua::state::raw_state(void)
{
    return _pimpl->lua_state;
}

Deleted stack_cleaner.cpp.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// Copyright 2011 Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
//   notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
//   notice, this list of conditions and the following disclaimer in the
//   documentation and/or other materials provided with the distribution.
// * Neither the name of Google Inc. nor the names of its contributors
//   may be used to endorse or promote products derived from this software
//   without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include <cassert>
#include <cstring>

#include "stack_cleaner.hpp"
#include "state.ipp"


/// Internal implementation for lutok::stack_cleaner.
struct lutok::stack_cleaner::impl {
    /// Reference to the Lua state this stack_cleaner refers to.
    state& state_ref;

    /// The depth of the Lua stack to be restored.
    unsigned int original_depth;

    /// Constructor.
    ///
    /// \param state_ref_ Reference to the Lua state.
    /// \param original_depth_ The depth of the Lua stack.
    impl(state& state_ref_, const unsigned int original_depth_) :
        state_ref(state_ref_),
        original_depth(original_depth_)
    {
    }
};


/// Creates a new stack cleaner.
///
/// This gathers the current height of the stack so that extra elements can be
/// popped during destruction.
///
/// \param state_ The Lua state.
lutok::stack_cleaner::stack_cleaner(state& state_) :
    _pimpl(new impl(state_, state_.get_top()))
{
}


/// Pops any values from the stack not known at construction time.
///
/// \pre The current height of the stack must be equal or greater to the height
/// of the stack when this object was instantiated.
lutok::stack_cleaner::~stack_cleaner(void)
{
    const unsigned int current_depth = _pimpl->state_ref.get_top();
    assert(current_depth >= _pimpl->original_depth);
    const unsigned int diff = current_depth - _pimpl->original_depth;
    if (diff > 0)
        _pimpl->state_ref.pop(diff);
}


/// Forgets about any elements currently in the stack.
///
/// This allows a function to return values on the stack because all the
/// elements that are currently in the stack will not be touched during
/// destruction when the function is called.
void
lutok::stack_cleaner::forget(void)
{
    _pimpl->original_depth = _pimpl->state_ref.get_top();
}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






















































































































































































Deleted state.cpp.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
// Copyright 2011 Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
//   notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
//   notice, this list of conditions and the following disclaimer in the
//   documentation and/or other materials provided with the distribution.
// * Neither the name of Google Inc. nor the names of its contributors
//   may be used to endorse or promote products derived from this software
//   without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

extern "C" {
#include <unistd.h>
}

#include <cassert>
#include <cstring>

#include "c_gate.hpp"
#include "exceptions.hpp"
#include "state.ipp"


namespace {


/// Wrapper around lua_getglobal to run in a protected environment.
///
/// \pre stack(-1) is the name of the global to get.
/// \post stack(-1) is the value of the global.
///
/// \param state The Lua C API state.
///
/// \return The number of return values pushed onto the stack.
static int
protected_getglobal(lua_State* state)
{
    lua_getglobal(state, lua_tostring(state, -1));
    return 1;
}


/// Wrapper around lua_gettable to run in a protected environment.
///
/// \pre stack(-2) is the table to get the element from.
/// \pre stack(-1) is the table index.
/// \post stack(-1) is the value of stack(-2)[stack(-1)].
///
/// \param state The Lua C API state.
///
/// \return The number of return values pushed onto the stack.
static int
protected_gettable(lua_State* state)
{
    lua_gettable(state, -2);
    return 1;
}


/// Wrapper around lua_next to run in a protected environment.
///
/// \pre stack(-2) is the table to get the next element from.
/// \pre stack(-1) is the last processed key.
/// \post stack(-1) is the value of next(stack(-2), stack(-1)).
///
/// \param state The Lua C API state.
///
/// \return The number of return values pushed onto the stack.
static int
protected_next(lua_State* state)
{
    const int more = lua_next(state, -2) != 0;
    lua_pushboolean(state, more);
    return more ? 3 : 1;
}


/// Wrapper around lua_setglobal to run in a protected environment.
///
/// \pre stack(-2) is the name of the global to set.
/// \pre stack(-1) is the value to set the global to.
///
/// \param state The Lua C API state.
///
/// \return The number of return values pushed onto the stack.
static int
protected_setglobal(lua_State* state)
{
    lua_setglobal(state, lua_tostring(state, -2));
    return 0;
}


/// Wrapper around lua_settable to run in a protected environment.
///
/// \pre stack(-3) is the table to set the element into.
/// \pre stack(-2) is the table index.
/// \pre stack(-1) is the value to set.
///
/// \param state The Lua C API state.
///
/// \return The number of return values pushed onto the stack.
static int
protected_settable(lua_State* state)
{
    lua_settable(state, -3);
    return 0;
}


/// Calls a C++ Lua function from a C calling environment.
///
/// Any errors reported by the C++ function are caught and reported to the
/// caller as Lua errors.
///
/// \param function The C++ function to call.
/// \param raw_state The raw Lua state.
///
/// \return The number of return values pushed onto the Lua stack by the
/// function.
static int
call_cxx_function_from_c(lutok::cxx_function function,
                         lua_State* raw_state) throw()
{
    char error_buf[1024];

    try {
        lutok::state state = lutok::state_c_gate::connect(raw_state);
        return function(state);
    } catch (const std::exception& e) {
        std::strncpy(error_buf, e.what(), sizeof(error_buf));
    } catch (...) {
        std::strncpy(error_buf, "Unhandled exception in Lua C++ hook",
                     sizeof(error_buf));
    }
    error_buf[sizeof(error_buf) - 1] = '\0';
    // We raise the Lua error from outside the try/catch context and we use
    // a stack-based buffer to hold the message to ensure that we do not leak
    // any C++ objects (and, as a likely result, memory) when Lua performs its
    // longjmp.
    return luaL_error(raw_state, "%s", error_buf);
}


/// Lua glue to call a C++ closure.
///
/// This Lua binding is actually a closure that we have constructed from the
/// state.push_cxx_closure() method.  The closure contains the same upvalues
/// provided by the user plus an extra upvalue that contains the address of the
/// C++ function we have to call.  All we do here is safely delegate the
/// execution to the wrapped C++ closure.
///
/// \param raw_state The Lua C API state.
///
/// \return The number of return values of the called closure.
static int
cxx_closure_trampoline(lua_State* raw_state)
{
    lutok::state state = lutok::state_c_gate::connect(raw_state);

    int nupvalues;
    {
        lua_Debug debug;
        lua_getstack(raw_state, 0, &debug);
        lua_getinfo(raw_state, "u", &debug);
        nupvalues = debug.nups;
    }

    lutok::cxx_function* function = state.to_userdata< lutok::cxx_function >(
        state.upvalue_index(nupvalues));
    return call_cxx_function_from_c(*function, raw_state);
}


/// Lua glue to call a C++ function.
///
/// This Lua binding is actually a closure that we have constructed from the
/// state.push_cxx_function() method.  The closure has a single upvalue that
/// contains the address of the C++ function we have to call.  All we do here is
/// safely delegate the execution to the wrapped C++ function.
///
/// \param raw_state The Lua C API state.
///
/// \return The number of return values of the called function.
static int
cxx_function_trampoline(lua_State* raw_state)
{
    lutok::state state = lutok::state_c_gate::connect(raw_state);
    lutok::cxx_function* function = state.to_userdata< lutok::cxx_function >(
        state.upvalue_index(1));
    return call_cxx_function_from_c(*function, raw_state);
}


}  // anonymous namespace


const int lutok::registry_index = LUA_REGISTRYINDEX;


/// Internal implementation for lutok::state.
struct lutok::state::impl {
    /// The Lua internal state.
    lua_State* lua_state;

    /// Whether we own the state or not (to decide if we close it).
    bool owned;

    /// Constructor.
    ///
    /// \param lua_ The Lua internal state.
    /// \param owned_ Whether we own the state or not.
    impl(lua_State* lua_, bool owned_) :
        lua_state(lua_),
        owned(owned_)
    {
    }
};


/// Initializes the Lua state.
///
/// You must share the same state object alongside the lifetime of your Lua
/// session.  As soon as the object is destroyed, the session is terminated.
lutok::state::state(void)
{
    lua_State* lua = luaL_newstate();
    if (lua == NULL)
        throw lutok::error("lua open failed");
    _pimpl.reset(new impl(lua, true));
}


/// Initializes the Lua state from an existing raw state.
///
/// Instances constructed using this method do NOT own the raw state.  This
/// means that, on exit, the state will not be destroyed.
///
/// \param raw_state_ The raw Lua state to wrap.
lutok::state::state(void* raw_state_) :
    _pimpl(new impl(reinterpret_cast< lua_State* >(raw_state_), false))
{
}


/// Destructor for the Lua state.
///
/// Closes the session unless it has already been closed by calling the
/// close() method.  It is recommended to explicitly close the session in the
/// code.
lutok::state::~state(void)
{
    if (_pimpl->owned && _pimpl->lua_state != NULL)
        close();
}


/// Terminates this Lua session.
///
/// It is recommended to call this instead of relying on the destructor to do
/// the cleanup, but it is not a requirement to use close().
///
/// \pre close() has not yet been called.
/// \pre The Lua stack is empty.  This is not truly necessary but ensures that
///     our code is consistent and clears the stack explicitly.
void
lutok::state::close(void)
{
    assert(_pimpl->lua_state != NULL);
    assert(lua_gettop(_pimpl->lua_state) == 0);
    lua_close(_pimpl->lua_state);
    _pimpl->lua_state = NULL;
}


/// Wrapper around lua_getglobal.
///
/// \param name The second parameter to lua_getglobal.
///
/// \throw api_error If lua_getglobal fails.
///
/// \warning Terminates execution if there is not enough memory to manipulate
/// the Lua stack.
void
lutok::state::get_global(const std::string& name)
{
    lua_pushcfunction(_pimpl->lua_state, protected_getglobal);
    lua_pushstring(_pimpl->lua_state, name.c_str());
    if (lua_pcall(_pimpl->lua_state, 1, 1, 0) != 0)
        throw lutok::api_error::from_stack(*this, "lua_getglobal");
}


/// Pushes a reference to the global table onto the stack.
///
/// This is a wrapper around the incompatible differences between Lua 5.1 and
/// 5.2 to access to the globals table.
///
/// \post state(-1) Contains the reference to the globals table.
void
lutok::state::get_global_table(void)
{
#if LUA_VERSION_NUM >= 502
    lua_pushvalue(_pimpl->lua_state, registry_index);
    lua_pushinteger(_pimpl->lua_state, LUA_RIDX_GLOBALS);
    lua_gettable(_pimpl->lua_state, -2);
    lua_remove(_pimpl->lua_state, -2);
#else
    lua_pushvalue(_pimpl->lua_state, LUA_GLOBALSINDEX);
#endif
}


/// Wrapper around luaL_getmetafield.
///
/// \param index The second parameter to luaL_getmetafield.
/// \param name The third parameter to luaL_getmetafield.
///
/// \return The return value of luaL_getmetafield.
///
/// \warning Terminates execution if there is not enough memory to manipulate
/// the Lua stack.
bool
lutok::state::get_metafield(const int index, const std::string& name)
{
    return luaL_getmetafield(_pimpl->lua_state, index, name.c_str()) != 0;
}


/// Wrapper around lua_getmetatable.
///
/// \param index The second parameter to lua_getmetatable.
///
/// \return The return value of lua_getmetatable.
bool
lutok::state::get_metatable(const int index)
{
    return lua_getmetatable(_pimpl->lua_state, index) != 0;
}


/// Wrapper around lua_gettable.
///
/// \param index The second parameter to lua_gettable.
///
/// \throw api_error If lua_gettable fails.
///
/// \warning Terminates execution if there is not enough memory to manipulate
/// the Lua stack.
void
lutok::state::get_table(const int index)
{
    assert(lua_gettop(_pimpl->lua_state) >= 2);
    lua_pushcfunction(_pimpl->lua_state, protected_gettable);
    lua_pushvalue(_pimpl->lua_state, index < 0 ? index - 1 : index);
    lua_pushvalue(_pimpl->lua_state, -3);
    if (lua_pcall(_pimpl->lua_state, 2, 1, 0) != 0)
        throw lutok::api_error::from_stack(*this, "lua_gettable");
    lua_remove(_pimpl->lua_state, -2);
}


/// Wrapper around lua_gettop.
///
/// \return The return value of lua_gettop.
int
lutok::state::get_top(void)
{
    return lua_gettop(_pimpl->lua_state);
}


/// Wrapper around lua_insert.
///
/// \param index The second parameter to lua_insert.
void
lutok::state::insert(const int index)
{
    lua_insert(_pimpl->lua_state, index);
}


/// Wrapper around lua_isboolean.
///
/// \param index The second parameter to lua_isboolean.
///
/// \return The return value of lua_isboolean.
bool
lutok::state::is_boolean(const int index)
{
    return lua_isboolean(_pimpl->lua_state, index);
}


/// Wrapper around lua_isfunction.
///
/// \param index The second parameter to lua_isfunction.
///
/// \return The return value of lua_isfunction.
bool
lutok::state::is_function(const int index)
{
    return lua_isfunction(_pimpl->lua_state, index);
}


/// Wrapper around lua_isnil.
///
/// \param index The second parameter to lua_isnil.
///
/// \return The return value of lua_isnil.
bool
lutok::state::is_nil(const int index)
{
    return lua_isnil(_pimpl->lua_state, index);
}


/// Wrapper around lua_isnumber.
///
/// \param index The second parameter to lua_isnumber.
///
/// \return The return value of lua_isnumber.
bool
lutok::state::is_number(const int index)
{
    return lua_isnumber(_pimpl->lua_state, index);
}


/// Wrapper around lua_isstring.
///
/// \param index The second parameter to lua_isstring.
///
/// \return The return value of lua_isstring.
bool
lutok::state::is_string(const int index)
{
    return lua_isstring(_pimpl->lua_state, index);
}


/// Wrapper around lua_istable.
///
/// \param index The second parameter to lua_istable.
///
/// \return The return value of lua_istable.
bool
lutok::state::is_table(const int index)
{
    return lua_istable(_pimpl->lua_state, index);
}


/// Wrapper around lua_isuserdata.
///
/// \param index The second parameter to lua_isuserdata.
///
/// \return The return value of lua_isuserdata.
bool
lutok::state::is_userdata(const int index)
{
    return lua_isuserdata(_pimpl->lua_state, index);
}


/// Wrapper around luaL_loadfile.
///
/// \param file The second parameter to luaL_loadfile.
///
/// \throw api_error If luaL_loadfile returns an error.
/// \throw file_not_found_error If the file cannot be accessed.
///
/// \warning Terminates execution if there is not enough memory.
void
lutok::state::load_file(const std::string& file)
{
    if (::access(file.c_str(), R_OK) == -1)
        throw lutok::file_not_found_error(file);
    if (luaL_loadfile(_pimpl->lua_state, file.c_str()) != 0)
        throw lutok::api_error::from_stack(*this, "luaL_loadfile");
}


/// Wrapper around luaL_loadstring.
///
/// \param str The second parameter to luaL_loadstring.
///
/// \throw api_error If luaL_loadstring returns an error.
///
/// \warning Terminates execution if there is not enough memory.
void
lutok::state::load_string(const std::string& str)
{
    if (luaL_loadstring(_pimpl->lua_state, str.c_str()) != 0)
        throw lutok::api_error::from_stack(*this, "luaL_loadstring");
}


/// Wrapper around lua_newtable.
///
/// \warning Terminates execution if there is not enough memory.
void
lutok::state::new_table(void)
{
    lua_newtable(_pimpl->lua_state);
}


/// Wrapper around lua_newuserdata.
///
/// This is internal.  The public type-safe interface of this method should be
/// used instead.
///
/// \param size The second parameter to lua_newuserdata.
///
/// \return The return value of lua_newuserdata.
///
/// \warning Terminates execution if there is not enough memory.
void*
lutok::state::new_userdata_voidp(const size_t size)
{
    return lua_newuserdata(_pimpl->lua_state, size);
}


/// Wrapper around lua_next.
///
/// \param index The second parameter to lua_next.
///
/// \return True if there are more elements to process; false otherwise.
///
/// \warning Terminates execution if there is not enough memory.
bool
lutok::state::next(const int index)
{
    assert(lua_istable(_pimpl->lua_state, index));
    assert(lua_gettop(_pimpl->lua_state) >= 1);
    lua_pushcfunction(_pimpl->lua_state, protected_next);
    lua_pushvalue(_pimpl->lua_state, index < 0 ? index - 1 : index);
    lua_pushvalue(_pimpl->lua_state, -3);
    if (lua_pcall(_pimpl->lua_state, 2, LUA_MULTRET, 0) != 0)
        throw lutok::api_error::from_stack(*this, "lua_next");
    const bool more = lua_toboolean(_pimpl->lua_state, -1);
    lua_pop(_pimpl->lua_state, 1);
    if (more)
        lua_remove(_pimpl->lua_state, -3);
    else
        lua_pop(_pimpl->lua_state, 1);
    return more;
}


/// Wrapper around luaL_openlibs.
///
/// \throw api_error If luaL_openlibs fails.
///
/// \warning Terminates execution if there is not enough memory.
void
lutok::state::open_all(void)
{
    luaL_openlibs(_pimpl->lua_state);
}


/// Wrapper around luaopen_base.
///
/// \throw api_error If luaopen_base fails.
///
/// \warning Terminates execution if there is not enough memory.
void
lutok::state::open_base(void)
{
    lua_pushcfunction(_pimpl->lua_state, luaopen_base);
    if (lua_pcall(_pimpl->lua_state, 0, 0, 0) != 0)
        throw lutok::api_error::from_stack(*this, "luaopen_base");
}


/// Wrapper around luaopen_string.
///
/// \throw api_error If luaopen_string fails.
///
/// \warning Terminates execution if there is not enough memory.
void
lutok::state::open_string(void)
{
#if LUA_VERSION_NUM >= 502
    luaL_requiref(_pimpl->lua_state, LUA_STRLIBNAME, luaopen_string, 1);
    lua_pop(_pimpl->lua_state, 1);
#else
    lua_pushcfunction(_pimpl->lua_state, luaopen_string);
    if (lua_pcall(_pimpl->lua_state, 0, 0, 0) != 0)
        throw lutok::api_error::from_stack(*this, "luaopen_string");
#endif
}


/// Wrapper around luaopen_table.
///
/// \throw api_error If luaopen_table fails.
///
/// \warning Terminates execution if there is not enough memory.
void
lutok::state::open_table(void)
{
#if LUA_VERSION_NUM >= 502
    luaL_requiref(_pimpl->lua_state, LUA_TABLIBNAME, luaopen_table, 1);
    lua_pop(_pimpl->lua_state, 1);
#else
    lua_pushcfunction(_pimpl->lua_state, luaopen_table);
    if (lua_pcall(_pimpl->lua_state, 0, 0, 0) != 0)
        throw lutok::api_error::from_stack(*this, "luaopen_table");
#endif
}


/// Wrapper around lua_pcall.
///
/// \param nargs The second parameter to lua_pcall.
/// \param nresults The third parameter to lua_pcall.
/// \param errfunc The fourth parameter to lua_pcall.
///
/// \throw api_error If lua_pcall returns an error.
void
lutok::state::pcall(const int nargs, const int nresults, const int errfunc)
{
    if (lua_pcall(_pimpl->lua_state, nargs, nresults, errfunc) != 0)
        throw lutok::api_error::from_stack(*this, "lua_pcall");
}


/// Wrapper around lua_pop.
///
/// \param count The second parameter to lua_pop.
void
lutok::state::pop(const int count)
{
    assert(count <= lua_gettop(_pimpl->lua_state));
    lua_pop(_pimpl->lua_state, count);
    assert(lua_gettop(_pimpl->lua_state) >= 0);
}


/// Wrapper around lua_pushboolean.
///
/// \param value The second parameter to lua_pushboolean.
void
lutok::state::push_boolean(const bool value)
{
    lua_pushboolean(_pimpl->lua_state, value ? 1 : 0);
}


/// Wrapper around lua_pushcclosure.
///
/// This is not a pure wrapper around lua_pushcclosure because this has to do
/// extra magic to allow passing C++ functions instead of plain C functions.
///
/// \param function The C++ function to be pushed as a closure.
/// \param nvalues The number of upvalues that the function receives.
void
lutok::state::push_cxx_closure(cxx_function function, const int nvalues)
{
    cxx_function *data = static_cast< cxx_function* >(
        lua_newuserdata(_pimpl->lua_state, sizeof(cxx_function)));
    *data = function;
    lua_pushcclosure(_pimpl->lua_state, cxx_closure_trampoline, nvalues + 1);
}


/// Wrapper around lua_pushcfunction.
///
/// This is not a pure wrapper around lua_pushcfunction because this has to do
/// extra magic to allow passing C++ functions instead of plain C functions.
///
/// \param function The C++ function to be pushed.
void
lutok::state::push_cxx_function(cxx_function function)
{
    cxx_function *data = static_cast< cxx_function* >(
        lua_newuserdata(_pimpl->lua_state, sizeof(cxx_function)));
    *data = function;
    lua_pushcclosure(_pimpl->lua_state, cxx_function_trampoline, 1);
}


/// Wrapper around lua_pushinteger.
///
/// \param value The second parameter to lua_pushinteger.
void
lutok::state::push_integer(const int value)
{
    lua_pushinteger(_pimpl->lua_state, value);
}


/// Wrapper around lua_pushnil.
void
lutok::state::push_nil(void)
{
    lua_pushnil(_pimpl->lua_state);
}


/// Wrapper around lua_pushstring.
///
/// \param str The second parameter to lua_pushstring.
///
/// \warning Terminates execution if there is not enough memory.
void
lutok::state::push_string(const std::string& str)
{
    lua_pushstring(_pimpl->lua_state, str.c_str());
}


/// Wrapper around lua_pushvalue.
///
/// \param index The second parameter to lua_pushvalue.
void
lutok::state::push_value(const int index)
{
    lua_pushvalue(_pimpl->lua_state, index);
}


/// Wrapper around lua_rawget.
///
/// \param index The second parameter to lua_rawget.
void
lutok::state::raw_get(const int index)
{
    lua_rawget(_pimpl->lua_state, index);
}


/// Wrapper around lua_rawset.
///
/// \param index The second parameter to lua_rawset.
///
/// \warning Terminates execution if there is not enough memory to manipulate
/// the Lua stack.
void
lutok::state::raw_set(const int index)
{
    lua_rawset(_pimpl->lua_state, index);
}


/// Wrapper around lua_setglobal.
///
/// \param name The second parameter to lua_setglobal.
///
/// \throw api_error If lua_setglobal fails.
///
/// \warning Terminates execution if there is not enough memory to manipulate
/// the Lua stack.
void
lutok::state::set_global(const std::string& name)
{
    lua_pushcfunction(_pimpl->lua_state, protected_setglobal);
    lua_pushstring(_pimpl->lua_state, name.c_str());
    lua_pushvalue(_pimpl->lua_state, -3);
    if (lua_pcall(_pimpl->lua_state, 2, 0, 0) != 0)
        throw lutok::api_error::from_stack(*this, "lua_setglobal");
    lua_pop(_pimpl->lua_state, 1);
}


/// Wrapper around lua_setmetatable.
///
/// \param index The second parameter to lua_setmetatable.
void
lutok::state::set_metatable(const int index)
{
    lua_setmetatable(_pimpl->lua_state, index);
}


/// Wrapper around lua_settable.
///
/// \param index The second parameter to lua_settable.
///
/// \throw api_error If lua_settable fails.
///
/// \warning Terminates execution if there is not enough memory to manipulate
/// the Lua stack.
void
lutok::state::set_table(const int index)
{
    lua_pushcfunction(_pimpl->lua_state, protected_settable);
    lua_pushvalue(_pimpl->lua_state, index < 0 ? index - 1 : index);
    lua_pushvalue(_pimpl->lua_state, -4);
    lua_pushvalue(_pimpl->lua_state, -4);
    if (lua_pcall(_pimpl->lua_state, 3, 0, 0) != 0)
        throw lutok::api_error::from_stack(*this, "lua_settable");
    lua_pop(_pimpl->lua_state, 2);
}


/// Wrapper around lua_toboolean.
///
/// \param index The second parameter to lua_toboolean.
///
/// \return The return value of lua_toboolean.
bool
lutok::state::to_boolean(const int index)
{
    assert(is_boolean(index));
    return lua_toboolean(_pimpl->lua_state, index);
}


/// Wrapper around lua_tointeger.
///
/// \param index The second parameter to lua_tointeger.
///
/// \return The return value of lua_tointeger.
long
lutok::state::to_integer(const int index)
{
    assert(is_number(index));
    return lua_tointeger(_pimpl->lua_state, index);
}


/// Wrapper around lua_touserdata.
///
/// This is internal.  The public type-safe interface of this method should be
/// used instead.
///
/// \param index The second parameter to lua_touserdata.
///
/// \return The return value of lua_touserdata.
///
/// \warning Terminates execution if there is not enough memory.
void*
lutok::state::to_userdata_voidp(const int index)
{
    return lua_touserdata(_pimpl->lua_state, index);
}



/// Wrapper around lua_tostring.
///
/// \param index The second parameter to lua_tostring.
///
/// \return The return value of lua_tostring.
///
/// \warning Terminates execution if there is not enough memory.
std::string
lutok::state::to_string(const int index)
{
    assert(is_string(index));
    const char *raw_string = lua_tostring(_pimpl->lua_state, index);
    // Note that the creation of a string object below (explicit for clarity)
    // implies that the raw string is duplicated and, henceforth, the string is
    // safe even if the corresponding element is popped from the Lua stack.
    return std::string(raw_string);
}


/// Wrapper around lua_upvalueindex.
///
/// \param index The first parameter to lua_upvalueindex.
///
/// \return The return value of lua_upvalueindex.
int
lutok::state::upvalue_index(const int index)
{
    return lua_upvalueindex(index);
}


/// Gets the internal lua_State object.
///
/// \return The raw Lua state.  This is returned as a void pointer to prevent
/// including the lua.hpp header file from our public interface.  The only way
/// to call this method is by using the c_gate module, and c_gate takes care of
/// casting this object to the appropriate type.
void*
lutok::state::raw_state(void)
{
    return _pimpl->lua_state;
}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Changes to tests/c_gate_test.cpp.

22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "xlua/c_gate.hpp"

#include <atf-c++.hpp>
#include <lua.hpp>

#include "xlua/state.ipp"
#include "xlua/test_utils.hpp"


ATF_TEST_CASE_WITHOUT_HEAD(connect);
ATF_TEST_CASE_BODY(connect)
{
    lua_State* raw_state = luaL_newstate();
    ATF_REQUIRE(raw_state != NULL);

    {
        lutok::state state = lutok::state_c_gate::connect(raw_state);
        lua_pushinteger(raw(state), 123);
    }
    // If the wrapper object had closed the Lua state, we could very well crash
    // here.
    ATF_REQUIRE_EQ(123, lua_tointeger(raw_state, -1));

    lua_close(raw_state);
}


ATF_TEST_CASE_WITHOUT_HEAD(c_state);
ATF_TEST_CASE_BODY(c_state)
{
    lutok::state state;
    state.push_integer(5);
    {
        lutok::state_c_gate gate(state);
        lua_State* raw_state = gate.c_state();
        ATF_REQUIRE_EQ(5, lua_tointeger(raw_state, -1));
    }
    state.pop(1);
}


ATF_INIT_TEST_CASES(tcs)
{
    ATF_ADD_TEST_CASE(tcs, c_state);
    ATF_ADD_TEST_CASE(tcs, connect);
}







|




|
|









|













|


|












22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include <xlua/c_gate.hpp>

#include <atf-c++.hpp>
#include <lua.hpp>

#include <xlua/state.ipp>
#include <xlua/test_utils.hpp>


ATF_TEST_CASE_WITHOUT_HEAD(connect);
ATF_TEST_CASE_BODY(connect)
{
    lua_State* raw_state = luaL_newstate();
    ATF_REQUIRE(raw_state != NULL);

    {
        xlua::state state = xlua::state_c_gate::connect(raw_state);
        lua_pushinteger(raw(state), 123);
    }
    // If the wrapper object had closed the Lua state, we could very well crash
    // here.
    ATF_REQUIRE_EQ(123, lua_tointeger(raw_state, -1));

    lua_close(raw_state);
}


ATF_TEST_CASE_WITHOUT_HEAD(c_state);
ATF_TEST_CASE_BODY(c_state)
{
    xlua::state state;
    state.push_integer(5);
    {
        xlua::state_c_gate gate(state);
        lua_State* raw_state = gate.c_state();
        ATF_REQUIRE_EQ(5, lua_tointeger(raw_state, -1));
    }
    state.pop(1);
}


ATF_INIT_TEST_CASES(tcs)
{
    ATF_ADD_TEST_CASE(tcs, c_state);
    ATF_ADD_TEST_CASE(tcs, connect);
}

Changes to tests/debug_test.cpp.

22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "xlua/debug.hpp"

#include <xlua/atf-c++.hpp>
#include <lua.hpp>

#include "xlua/state.ipp"
#include "xlua/test_utils.hpp"


ATF_TEST_CASE_WITHOUT_HEAD(get_info);
ATF_TEST_CASE_BODY(get_info)
{
    lutok::state state;
    ATF_REQUIRE(luaL_dostring(raw(state), "\n\nfunction hello() end\n"
                              "return hello") == 0);
    lutok::debug debug;
    debug.get_info(state, ">S");
    ATF_REQUIRE_EQ(3, debug.line_defined());
}


ATF_TEST_CASE_WITHOUT_HEAD(get_stack);
ATF_TEST_CASE_BODY(get_stack)
{
    lutok::state state;
    ATF_REQUIRE(luaL_dostring(raw(state), "error('Hello')") == 1);
    lutok::debug debug;
    debug.get_stack(state, 0);
    lua_pop(raw(state), 1);
    // Not sure if we can actually validate anything here, other than we did not
    // crash... (because get_stack only is supposed to update internal values of
    // the debug structure).
}


ATF_INIT_TEST_CASES(tcs)
{
    ATF_ADD_TEST_CASE(tcs, get_info);
    ATF_ADD_TEST_CASE(tcs, get_stack);
}







|




|
|





|


|








|

|













22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include <xlua/debug.hpp>

#include <xlua/atf-c++.hpp>
#include <lua.hpp>

#include <xlua/state.ipp>
#include <xlua/test_utils.hpp>


ATF_TEST_CASE_WITHOUT_HEAD(get_info);
ATF_TEST_CASE_BODY(get_info)
{
    xlua::state state;
    ATF_REQUIRE(luaL_dostring(raw(state), "\n\nfunction hello() end\n"
                              "return hello") == 0);
    xlua::debug debug;
    debug.get_info(state, ">S");
    ATF_REQUIRE_EQ(3, debug.line_defined());
}


ATF_TEST_CASE_WITHOUT_HEAD(get_stack);
ATF_TEST_CASE_BODY(get_stack)
{
    xlua::state state;
    ATF_REQUIRE(luaL_dostring(raw(state), "error('Hello')") == 1);
    xlua::debug debug;
    debug.get_stack(state, 0);
    lua_pop(raw(state), 1);
    // Not sure if we can actually validate anything here, other than we did not
    // crash... (because get_stack only is supposed to update internal values of
    // the debug structure).
}


ATF_INIT_TEST_CASES(tcs)
{
    ATF_ADD_TEST_CASE(tcs, get_info);
    ATF_ADD_TEST_CASE(tcs, get_stack);
}

Changes to tests/exceptions_test.cpp.

22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "xlua/exceptions.hpp"

#include <cstring>

#include <atf-c++.hpp>

#include "xlua/state.ipp"


ATF_TEST_CASE_WITHOUT_HEAD(error);
ATF_TEST_CASE_BODY(error)
{
    const lutok::error e("Some text");
    ATF_REQUIRE(std::strcmp("Some text", e.what()) == 0);
}


ATF_TEST_CASE_WITHOUT_HEAD(api_error__explicit);
ATF_TEST_CASE_BODY(api_error__explicit)
{
    const lutok::api_error e("some_function", "Some text");
    ATF_REQUIRE(std::strcmp("Some text", e.what()) == 0);
    ATF_REQUIRE_EQ("some_function", e.api_function());
}


ATF_TEST_CASE_WITHOUT_HEAD(api_error__from_stack);
ATF_TEST_CASE_BODY(api_error__from_stack)
{
    lutok::state state;
    state.push_integer(123);
    state.push_string("The error message");
    const lutok::api_error e = lutok::api_error::from_stack(state,
                                                            "the_function");
    ATF_REQUIRE_EQ(1, state.get_top());
    ATF_REQUIRE_EQ(123, state.to_integer(-1));
    state.pop(1);
    ATF_REQUIRE(std::strcmp("The error message", e.what()) == 0);
    ATF_REQUIRE_EQ("the_function", e.api_function());
}


ATF_TEST_CASE_WITHOUT_HEAD(file_not_found_error);
ATF_TEST_CASE_BODY(file_not_found_error)
{
    const lutok::file_not_found_error e("missing-file");
    ATF_REQUIRE(std::strcmp("File 'missing-file' not found", e.what()) == 0);
    ATF_REQUIRE_EQ("missing-file", e.filename());
}


ATF_INIT_TEST_CASES(tcs)
{







|





|





|







|








|


|












|







22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include <xlua/exceptions.hpp>

#include <cstring>

#include <atf-c++.hpp>

#include <xlua/state.ipp>


ATF_TEST_CASE_WITHOUT_HEAD(error);
ATF_TEST_CASE_BODY(error)
{
    const xlua::error e("Some text");
    ATF_REQUIRE(std::strcmp("Some text", e.what()) == 0);
}


ATF_TEST_CASE_WITHOUT_HEAD(api_error__explicit);
ATF_TEST_CASE_BODY(api_error__explicit)
{
    const xlua::api_error e("some_function", "Some text");
    ATF_REQUIRE(std::strcmp("Some text", e.what()) == 0);
    ATF_REQUIRE_EQ("some_function", e.api_function());
}


ATF_TEST_CASE_WITHOUT_HEAD(api_error__from_stack);
ATF_TEST_CASE_BODY(api_error__from_stack)
{
    xlua::state state;
    state.push_integer(123);
    state.push_string("The error message");
    const xlua::api_error e = xlua::api_error::from_stack(state,
                                                            "the_function");
    ATF_REQUIRE_EQ(1, state.get_top());
    ATF_REQUIRE_EQ(123, state.to_integer(-1));
    state.pop(1);
    ATF_REQUIRE(std::strcmp("The error message", e.what()) == 0);
    ATF_REQUIRE_EQ("the_function", e.api_function());
}


ATF_TEST_CASE_WITHOUT_HEAD(file_not_found_error);
ATF_TEST_CASE_BODY(file_not_found_error)
{
    const xlua::file_not_found_error e("missing-file");
    ATF_REQUIRE(std::strcmp("File 'missing-file' not found", e.what()) == 0);
    ATF_REQUIRE_EQ("missing-file", e.filename());
}


ATF_INIT_TEST_CASES(tcs)
{

Changes to tests/operations_test.cpp.

22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
..
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
..
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
...
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
...
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "xlua/operations.hpp"

#include <fstream>

#include <atf-c++.hpp>

#include "xlua/exceptions.hpp"
#include "xlua/state.ipp"
#include "xlua/test_utils.hpp"


namespace {


/// Addition function for injection into Lua.
///
................................................................................
/// \pre stack(-1) The second summand.
/// \post stack(-1) The result of the sum.
///
/// \param state The Lua state.
///
/// \return The number of results (1).
static int
hook_add(lutok::state& state)
{
    state.push_integer(state.to_integer(-1) + state.to_integer(-2));
    return 1;
}


/// Multiplication function for injection into Lua.
................................................................................
/// \pre stack(-1) The second factor.
/// \post stack(-1) The product.
///
/// \param state The Lua state.
///
/// \return The number of results (1).
static int
hook_multiply(lutok::state& state)
{
    state.push_integer(state.to_integer(-1) * state.to_integer(-2));
    return 1;
}


}  // anonymous namespace


ATF_TEST_CASE_WITHOUT_HEAD(create_module__empty);
ATF_TEST_CASE_BODY(create_module__empty)
{
    lutok::state state;
    std::map< std::string, lutok::cxx_function > members;
    lutok::create_module(state, "my_math", members);

    state.open_base();
    lutok::do_string(state, "return next(my_math) == nil", 0, 1, 0);
    ATF_REQUIRE(state.to_boolean(-1));
    state.pop(1);
}


ATF_TEST_CASE_WITHOUT_HEAD(create_module__one);
ATF_TEST_CASE_BODY(create_module__one)
{
    lutok::state state;
    std::map< std::string, lutok::cxx_function > members;
    members["add"] = hook_add;
    lutok::create_module(state, "my_math", members);

    lutok::do_string(state, "return my_math.add(10, 20)", 0, 1, 0);
    ATF_REQUIRE_EQ(30, state.to_integer(-1));
    state.pop(1);
}


ATF_TEST_CASE_WITHOUT_HEAD(create_module__many);
ATF_TEST_CASE_BODY(create_module__many)
{
    lutok::state state;
    std::map< std::string, lutok::cxx_function > members;
    members["add"] = hook_add;
    members["multiply"] = hook_multiply;
    members["add2"] = hook_add;
    lutok::create_module(state, "my_math", members);

    lutok::do_string(state, "return my_math.add(10, 20)", 0, 1, 0);
    ATF_REQUIRE_EQ(30, state.to_integer(-1));
    lutok::do_string(state, "return my_math.multiply(10, 20)", 0, 1, 0);
    ATF_REQUIRE_EQ(200, state.to_integer(-1));
    lutok::do_string(state, "return my_math.add2(20, 30)", 0, 1, 0);
    ATF_REQUIRE_EQ(50, state.to_integer(-1));
    state.pop(3);
}


ATF_TEST_CASE_WITHOUT_HEAD(do_file__some_args);
ATF_TEST_CASE_BODY(do_file__some_args)
{
    std::ofstream output("test.lua");
    output << "local a1, a2 = ...\nreturn a1 * 2, a2 * 2\n";
    output.close();

    lutok::state state;
    state.push_integer(456);
    state.push_integer(3);
    state.push_integer(5);
    state.push_integer(123);
    ATF_REQUIRE_EQ(2, lutok::do_file(state, "test.lua", 3, -1, 0));
    ATF_REQUIRE_EQ(3, state.get_top());
    ATF_REQUIRE_EQ(456, state.to_integer(-3));
    ATF_REQUIRE_EQ(6, state.to_integer(-2));
    ATF_REQUIRE_EQ(10, state.to_integer(-1));
    state.pop(3);
}

................................................................................
ATF_TEST_CASE_WITHOUT_HEAD(do_file__any_results);
ATF_TEST_CASE_BODY(do_file__any_results)
{
    std::ofstream output("test.lua");
    output << "return 10, 20, 30\n";
    output.close();

    lutok::state state;
    ATF_REQUIRE_EQ(3, lutok::do_file(state, "test.lua", 0, -1, 0));
    ATF_REQUIRE_EQ(3, state.get_top());
    ATF_REQUIRE_EQ(10, state.to_integer(-3));
    ATF_REQUIRE_EQ(20, state.to_integer(-2));
    ATF_REQUIRE_EQ(30, state.to_integer(-1));
    state.pop(3);
}

................................................................................
ATF_TEST_CASE_WITHOUT_HEAD(do_file__no_results);
ATF_TEST_CASE_BODY(do_file__no_results)
{
    std::ofstream output("test.lua");
    output << "return 10, 20, 30\n";
    output.close();

    lutok::state state;
    ATF_REQUIRE_EQ(0, lutok::do_file(state, "test.lua", 0, 0, 0));
    ATF_REQUIRE_EQ(0, state.get_top());
}


ATF_TEST_CASE_WITHOUT_HEAD(do_file__many_results);
ATF_TEST_CASE_BODY(do_file__many_results)
{
    std::ofstream output("test.lua");
    output << "return 10, 20, 30\n";
    output.close();

    lutok::state state;
    ATF_REQUIRE_EQ(2, lutok::do_file(state, "test.lua", 0, 2, 0));
    ATF_REQUIRE_EQ(2, state.get_top());
    ATF_REQUIRE_EQ(10, state.to_integer(-2));
    ATF_REQUIRE_EQ(20, state.to_integer(-1));
    state.pop(2);
}


ATF_TEST_CASE_WITHOUT_HEAD(do_file__not_found);
ATF_TEST_CASE_BODY(do_file__not_found)
{
    lutok::state state;
    stack_balance_checker checker(state);
    ATF_REQUIRE_THROW_RE(lutok::file_not_found_error, "missing.lua",
                         lutok::do_file(state, "missing.lua", 0, 0, 0));
}


ATF_TEST_CASE_WITHOUT_HEAD(do_file__error);
ATF_TEST_CASE_BODY(do_file__error)
{
    std::ofstream output("test.lua");
    output << "a b c\n";
    output.close();

    lutok::state state;
    stack_balance_checker checker(state);
    ATF_REQUIRE_THROW_RE(lutok::error, "Failed to load Lua file 'test.lua'",
                         lutok::do_file(state, "test.lua", 0, 0, 0));
}


ATF_TEST_CASE_WITHOUT_HEAD(do_file__error_with_errfunc);
ATF_TEST_CASE_BODY(do_file__error_with_errfunc)
{
    std::ofstream output("test.lua");
    output << "unknown_function()\n";
    output.close();

    lutok::state state;
    lutok::eval(state, "function(message) return 'This is an error!' end", 1);
    {
        stack_balance_checker checker(state);
        ATF_REQUIRE_THROW_RE(lutok::error, "This is an error!",
                             lutok::do_file(state, "test.lua", 0, 0, -2));
    }
    state.pop(1);
}


ATF_TEST_CASE_WITHOUT_HEAD(do_string__some_args);
ATF_TEST_CASE_BODY(do_string__some_args)
{
    lutok::state state;
    state.push_integer(456);
    state.push_integer(3);
    state.push_integer(5);
    state.push_integer(123);
    ATF_REQUIRE_EQ(2, lutok::do_string(
        state, "local a1, a2 = ...\nreturn a1 * 2, a2 * 2\n", 3, -1, 0));
    ATF_REQUIRE_EQ(3, state.get_top());
    ATF_REQUIRE_EQ(456, state.to_integer(-3));
    ATF_REQUIRE_EQ(6, state.to_integer(-2));
    ATF_REQUIRE_EQ(10, state.to_integer(-1));
    state.pop(3);
}


ATF_TEST_CASE_WITHOUT_HEAD(do_string__any_results);
ATF_TEST_CASE_BODY(do_string__any_results)
{
    lutok::state state;
    ATF_REQUIRE_EQ(3, lutok::do_string(state, "return 10, 20, 30", 0, -1, 0));
    ATF_REQUIRE_EQ(3, state.get_top());
    ATF_REQUIRE_EQ(10, state.to_integer(-3));
    ATF_REQUIRE_EQ(20, state.to_integer(-2));
    ATF_REQUIRE_EQ(30, state.to_integer(-1));
    state.pop(3);
}


ATF_TEST_CASE_WITHOUT_HEAD(do_string__no_results);
ATF_TEST_CASE_BODY(do_string__no_results)
{
    lutok::state state;
    ATF_REQUIRE_EQ(0, lutok::do_string(state, "return 10, 20, 30", 0, 0, 0));
    ATF_REQUIRE_EQ(0, state.get_top());
}


ATF_TEST_CASE_WITHOUT_HEAD(do_string__many_results);
ATF_TEST_CASE_BODY(do_string__many_results)
{
    lutok::state state;
    ATF_REQUIRE_EQ(2, lutok::do_string(state, "return 10, 20, 30", 0, 2, 0));
    ATF_REQUIRE_EQ(2, state.get_top());
    ATF_REQUIRE_EQ(10, state.to_integer(-2));
    ATF_REQUIRE_EQ(20, state.to_integer(-1));
    state.pop(2);
}


ATF_TEST_CASE_WITHOUT_HEAD(do_string__error);
ATF_TEST_CASE_BODY(do_string__error)
{
    lutok::state state;
    stack_balance_checker checker(state);
    ATF_REQUIRE_THROW_RE(lutok::error, "Failed to process Lua string 'a b c'",
                         lutok::do_string(state, "a b c", 0, 0, 0));
}


ATF_TEST_CASE_WITHOUT_HEAD(do_string__error_with_errfunc);
ATF_TEST_CASE_BODY(do_string__error_with_errfunc)
{
    lutok::state state;
    lutok::eval(state, "function(message) return 'This is an error!' end", 1);
    {
        stack_balance_checker checker(state);
        ATF_REQUIRE_THROW_RE(lutok::error, "This is an error!",
                             lutok::do_string(state, "unknown_function()",
                                              0, 0, -2));
    }
    state.pop(1);
}


ATF_TEST_CASE_WITHOUT_HEAD(eval__one_result);
ATF_TEST_CASE_BODY(eval__one_result)
{
    lutok::state state;
    stack_balance_checker checker(state);
    lutok::eval(state, "3 + 10", 1);
    ATF_REQUIRE_EQ(13, state.to_integer(-1));
    state.pop(1);
}


ATF_TEST_CASE_WITHOUT_HEAD(eval__many_results);
ATF_TEST_CASE_BODY(eval__many_results)
{
    lutok::state state;
    stack_balance_checker checker(state);
    lutok::eval(state, "5, 8, 10", 3);
    ATF_REQUIRE_EQ(5, state.to_integer(-3));
    ATF_REQUIRE_EQ(8, state.to_integer(-2));
    ATF_REQUIRE_EQ(10, state.to_integer(-1));
    state.pop(3);
}


ATF_TEST_CASE_WITHOUT_HEAD(eval__error);
ATF_TEST_CASE_BODY(eval__error)
{
    lutok::state state;
    stack_balance_checker checker(state);
    ATF_REQUIRE_THROW(lutok::error,
                      lutok::eval(state, "non_existent.method()", 1));
}


ATF_INIT_TEST_CASES(tcs)
{
    ATF_ADD_TEST_CASE(tcs, create_module__empty);
    ATF_ADD_TEST_CASE(tcs, create_module__one);







|





|
|
|







 







|







 







|












|
|
|


|








|
|

|

|








|
|



|

|

|

|












|




|







 







|
|







 







|
|











|
|










|

|
|










|

|
|










|
|


|
|








|




|












|
|











|
|







|
|










|

|
|






|
|


|
|









|

|








|

|










|

|
|







22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
..
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
..
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
...
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
...
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include <xlua/operations.hpp>

#include <fstream>

#include <atf-c++.hpp>

#include <xlua/exceptions.hpp>
#include <xlua/state.ipp>
#include <xlua/test_utils.hpp>


namespace {


/// Addition function for injection into Lua.
///
................................................................................
/// \pre stack(-1) The second summand.
/// \post stack(-1) The result of the sum.
///
/// \param state The Lua state.
///
/// \return The number of results (1).
static int
hook_add(xlua::state& state)
{
    state.push_integer(state.to_integer(-1) + state.to_integer(-2));
    return 1;
}


/// Multiplication function for injection into Lua.
................................................................................
/// \pre stack(-1) The second factor.
/// \post stack(-1) The product.
///
/// \param state The Lua state.
///
/// \return The number of results (1).
static int
hook_multiply(xlua::state& state)
{
    state.push_integer(state.to_integer(-1) * state.to_integer(-2));
    return 1;
}


}  // anonymous namespace


ATF_TEST_CASE_WITHOUT_HEAD(create_module__empty);
ATF_TEST_CASE_BODY(create_module__empty)
{
    xlua::state state;
    std::map< std::string, xlua::cxx_function > members;
    xlua::create_module(state, "my_math", members);

    state.open_base();
    xlua::do_string(state, "return next(my_math) == nil", 0, 1, 0);
    ATF_REQUIRE(state.to_boolean(-1));
    state.pop(1);
}


ATF_TEST_CASE_WITHOUT_HEAD(create_module__one);
ATF_TEST_CASE_BODY(create_module__one)
{
    xlua::state state;
    std::map< std::string, xlua::cxx_function > members;
    members["add"] = hook_add;
    xlua::create_module(state, "my_math", members);

    xlua::do_string(state, "return my_math.add(10, 20)", 0, 1, 0);
    ATF_REQUIRE_EQ(30, state.to_integer(-1));
    state.pop(1);
}


ATF_TEST_CASE_WITHOUT_HEAD(create_module__many);
ATF_TEST_CASE_BODY(create_module__many)
{
    xlua::state state;
    std::map< std::string, xlua::cxx_function > members;
    members["add"] = hook_add;
    members["multiply"] = hook_multiply;
    members["add2"] = hook_add;
    xlua::create_module(state, "my_math", members);

    xlua::do_string(state, "return my_math.add(10, 20)", 0, 1, 0);
    ATF_REQUIRE_EQ(30, state.to_integer(-1));
    xlua::do_string(state, "return my_math.multiply(10, 20)", 0, 1, 0);
    ATF_REQUIRE_EQ(200, state.to_integer(-1));
    xlua::do_string(state, "return my_math.add2(20, 30)", 0, 1, 0);
    ATF_REQUIRE_EQ(50, state.to_integer(-1));
    state.pop(3);
}


ATF_TEST_CASE_WITHOUT_HEAD(do_file__some_args);
ATF_TEST_CASE_BODY(do_file__some_args)
{
    std::ofstream output("test.lua");
    output << "local a1, a2 = ...\nreturn a1 * 2, a2 * 2\n";
    output.close();

    xlua::state state;
    state.push_integer(456);
    state.push_integer(3);
    state.push_integer(5);
    state.push_integer(123);
    ATF_REQUIRE_EQ(2, xlua::do_file(state, "test.lua", 3, -1, 0));
    ATF_REQUIRE_EQ(3, state.get_top());
    ATF_REQUIRE_EQ(456, state.to_integer(-3));
    ATF_REQUIRE_EQ(6, state.to_integer(-2));
    ATF_REQUIRE_EQ(10, state.to_integer(-1));
    state.pop(3);
}

................................................................................
ATF_TEST_CASE_WITHOUT_HEAD(do_file__any_results);
ATF_TEST_CASE_BODY(do_file__any_results)
{
    std::ofstream output("test.lua");
    output << "return 10, 20, 30\n";
    output.close();

    xlua::state state;
    ATF_REQUIRE_EQ(3, xlua::do_file(state, "test.lua", 0, -1, 0));
    ATF_REQUIRE_EQ(3, state.get_top());
    ATF_REQUIRE_EQ(10, state.to_integer(-3));
    ATF_REQUIRE_EQ(20, state.to_integer(-2));
    ATF_REQUIRE_EQ(30, state.to_integer(-1));
    state.pop(3);
}

................................................................................
ATF_TEST_CASE_WITHOUT_HEAD(do_file__no_results);
ATF_TEST_CASE_BODY(do_file__no_results)
{
    std::ofstream output("test.lua");
    output << "return 10, 20, 30\n";
    output.close();

    xlua::state state;
    ATF_REQUIRE_EQ(0, xlua::do_file(state, "test.lua", 0, 0, 0));
    ATF_REQUIRE_EQ(0, state.get_top());
}


ATF_TEST_CASE_WITHOUT_HEAD(do_file__many_results);
ATF_TEST_CASE_BODY(do_file__many_results)
{
    std::ofstream output("test.lua");
    output << "return 10, 20, 30\n";
    output.close();

    xlua::state state;
    ATF_REQUIRE_EQ(2, xlua::do_file(state, "test.lua", 0, 2, 0));
    ATF_REQUIRE_EQ(2, state.get_top());
    ATF_REQUIRE_EQ(10, state.to_integer(-2));
    ATF_REQUIRE_EQ(20, state.to_integer(-1));
    state.pop(2);
}


ATF_TEST_CASE_WITHOUT_HEAD(do_file__not_found);
ATF_TEST_CASE_BODY(do_file__not_found)
{
    xlua::state state;
    stack_balance_checker checker(state);
    ATF_REQUIRE_THROW_RE(xlua::file_not_found_error, "missing.lua",
                         xlua::do_file(state, "missing.lua", 0, 0, 0));
}


ATF_TEST_CASE_WITHOUT_HEAD(do_file__error);
ATF_TEST_CASE_BODY(do_file__error)
{
    std::ofstream output("test.lua");
    output << "a b c\n";
    output.close();

    xlua::state state;
    stack_balance_checker checker(state);
    ATF_REQUIRE_THROW_RE(xlua::error, "Failed to load Lua file 'test.lua'",
                         xlua::do_file(state, "test.lua", 0, 0, 0));
}


ATF_TEST_CASE_WITHOUT_HEAD(do_file__error_with_errfunc);
ATF_TEST_CASE_BODY(do_file__error_with_errfunc)
{
    std::ofstream output("test.lua");
    output << "unknown_function()\n";
    output.close();

    xlua::state state;
    xlua::eval(state, "function(message) return 'This is an error!' end", 1);
    {
        stack_balance_checker checker(state);
        ATF_REQUIRE_THROW_RE(xlua::error, "This is an error!",
                             xlua::do_file(state, "test.lua", 0, 0, -2));
    }
    state.pop(1);
}


ATF_TEST_CASE_WITHOUT_HEAD(do_string__some_args);
ATF_TEST_CASE_BODY(do_string__some_args)
{
    xlua::state state;
    state.push_integer(456);
    state.push_integer(3);
    state.push_integer(5);
    state.push_integer(123);
    ATF_REQUIRE_EQ(2, xlua::do_string(
        state, "local a1, a2 = ...\nreturn a1 * 2, a2 * 2\n", 3, -1, 0));
    ATF_REQUIRE_EQ(3, state.get_top());
    ATF_REQUIRE_EQ(456, state.to_integer(-3));
    ATF_REQUIRE_EQ(6, state.to_integer(-2));
    ATF_REQUIRE_EQ(10, state.to_integer(-1));
    state.pop(3);
}


ATF_TEST_CASE_WITHOUT_HEAD(do_string__any_results);
ATF_TEST_CASE_BODY(do_string__any_results)
{
    xlua::state state;
    ATF_REQUIRE_EQ(3, xlua::do_string(state, "return 10, 20, 30", 0, -1, 0));
    ATF_REQUIRE_EQ(3, state.get_top());
    ATF_REQUIRE_EQ(10, state.to_integer(-3));
    ATF_REQUIRE_EQ(20, state.to_integer(-2));
    ATF_REQUIRE_EQ(30, state.to_integer(-1));
    state.pop(3);
}


ATF_TEST_CASE_WITHOUT_HEAD(do_string__no_results);
ATF_TEST_CASE_BODY(do_string__no_results)
{
    xlua::state state;
    ATF_REQUIRE_EQ(0, xlua::do_string(state, "return 10, 20, 30", 0, 0, 0));
    ATF_REQUIRE_EQ(0, state.get_top());
}


ATF_TEST_CASE_WITHOUT_HEAD(do_string__many_results);
ATF_TEST_CASE_BODY(do_string__many_results)
{
    xlua::state state;
    ATF_REQUIRE_EQ(2, xlua::do_string(state, "return 10, 20, 30", 0, 2, 0));
    ATF_REQUIRE_EQ(2, state.get_top());
    ATF_REQUIRE_EQ(10, state.to_integer(-2));
    ATF_REQUIRE_EQ(20, state.to_integer(-1));
    state.pop(2);
}


ATF_TEST_CASE_WITHOUT_HEAD(do_string__error);
ATF_TEST_CASE_BODY(do_string__error)
{
    xlua::state state;
    stack_balance_checker checker(state);
    ATF_REQUIRE_THROW_RE(xlua::error, "Failed to process Lua string 'a b c'",
                         xlua::do_string(state, "a b c", 0, 0, 0));
}


ATF_TEST_CASE_WITHOUT_HEAD(do_string__error_with_errfunc);
ATF_TEST_CASE_BODY(do_string__error_with_errfunc)
{
    xlua::state state;
    xlua::eval(state, "function(message) return 'This is an error!' end", 1);
    {
        stack_balance_checker checker(state);
        ATF_REQUIRE_THROW_RE(xlua::error, "This is an error!",
                             xlua::do_string(state, "unknown_function()",
                                              0, 0, -2));
    }
    state.pop(1);
}


ATF_TEST_CASE_WITHOUT_HEAD(eval__one_result);
ATF_TEST_CASE_BODY(eval__one_result)
{
    xlua::state state;
    stack_balance_checker checker(state);
    xlua::eval(state, "3 + 10", 1);
    ATF_REQUIRE_EQ(13, state.to_integer(-1));
    state.pop(1);
}


ATF_TEST_CASE_WITHOUT_HEAD(eval__many_results);
ATF_TEST_CASE_BODY(eval__many_results)
{
    xlua::state state;
    stack_balance_checker checker(state);
    xlua::eval(state, "5, 8, 10", 3);
    ATF_REQUIRE_EQ(5, state.to_integer(-3));
    ATF_REQUIRE_EQ(8, state.to_integer(-2));
    ATF_REQUIRE_EQ(10, state.to_integer(-1));
    state.pop(3);
}


ATF_TEST_CASE_WITHOUT_HEAD(eval__error);
ATF_TEST_CASE_BODY(eval__error)
{
    xlua::state state;
    stack_balance_checker checker(state);
    ATF_REQUIRE_THROW(xlua::error,
                      xlua::eval(state, "non_existent.method()", 1));
}


ATF_INIT_TEST_CASES(tcs)
{
    ATF_ADD_TEST_CASE(tcs, create_module__empty);
    ATF_ADD_TEST_CASE(tcs, create_module__one);

Changes to tests/stack_cleaner_test.cpp.

22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
..
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "xlua/stack_cleaner.hpp"

#include <atf-c++.hpp>


ATF_TEST_CASE_WITHOUT_HEAD(empty);
ATF_TEST_CASE_BODY(empty)
{
    lutok::state state;
    {
        lutok::stack_cleaner cleaner(state);
        ATF_REQUIRE_EQ(0, state.get_top());
    }
    ATF_REQUIRE_EQ(0, state.get_top());
}


ATF_TEST_CASE_WITHOUT_HEAD(some);
ATF_TEST_CASE_BODY(some)
{
    lutok::state state;
    {
        lutok::stack_cleaner cleaner(state);
        state.push_integer(15);
        ATF_REQUIRE_EQ(1, state.get_top());
        state.push_integer(30);
        ATF_REQUIRE_EQ(2, state.get_top());
    }
    ATF_REQUIRE_EQ(0, state.get_top());
}


ATF_TEST_CASE_WITHOUT_HEAD(nested);
ATF_TEST_CASE_BODY(nested)
{
    lutok::state state;
    {
        lutok::stack_cleaner cleaner1(state);
        state.push_integer(10);
        ATF_REQUIRE_EQ(1, state.get_top());
        ATF_REQUIRE_EQ(10, state.to_integer(-1));
        {
            lutok::stack_cleaner cleaner2(state);
            state.push_integer(20);
            ATF_REQUIRE_EQ(2, state.get_top());
            ATF_REQUIRE_EQ(20, state.to_integer(-1));
            ATF_REQUIRE_EQ(10, state.to_integer(-2));
        }
        ATF_REQUIRE_EQ(1, state.get_top());
        ATF_REQUIRE_EQ(10, state.to_integer(-1));
................................................................................
    ATF_REQUIRE_EQ(0, state.get_top());
}


ATF_TEST_CASE_WITHOUT_HEAD(forget);
ATF_TEST_CASE_BODY(forget)
{
    lutok::state state;
    {
        lutok::stack_cleaner cleaner(state);
        state.push_integer(15);
        state.push_integer(30);
        cleaner.forget();
        state.push_integer(60);
        ATF_REQUIRE_EQ(3, state.get_top());
    }
    ATF_REQUIRE_EQ(2, state.get_top());







|







|

|









|

|












|

|




|







 







|

|







22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
..
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include <xlua/stack_cleaner.hpp>

#include <atf-c++.hpp>


ATF_TEST_CASE_WITHOUT_HEAD(empty);
ATF_TEST_CASE_BODY(empty)
{
    xlua::state state;
    {
        xlua::stack_cleaner cleaner(state);
        ATF_REQUIRE_EQ(0, state.get_top());
    }
    ATF_REQUIRE_EQ(0, state.get_top());
}


ATF_TEST_CASE_WITHOUT_HEAD(some);
ATF_TEST_CASE_BODY(some)
{
    xlua::state state;
    {
        xlua::stack_cleaner cleaner(state);
        state.push_integer(15);
        ATF_REQUIRE_EQ(1, state.get_top());
        state.push_integer(30);
        ATF_REQUIRE_EQ(2, state.get_top());
    }
    ATF_REQUIRE_EQ(0, state.get_top());
}


ATF_TEST_CASE_WITHOUT_HEAD(nested);
ATF_TEST_CASE_BODY(nested)
{
    xlua::state state;
    {
        xlua::stack_cleaner cleaner1(state);
        state.push_integer(10);
        ATF_REQUIRE_EQ(1, state.get_top());
        ATF_REQUIRE_EQ(10, state.to_integer(-1));
        {
            xlua::stack_cleaner cleaner2(state);
            state.push_integer(20);
            ATF_REQUIRE_EQ(2, state.get_top());
            ATF_REQUIRE_EQ(20, state.to_integer(-1));
            ATF_REQUIRE_EQ(10, state.to_integer(-2));
        }
        ATF_REQUIRE_EQ(1, state.get_top());
        ATF_REQUIRE_EQ(10, state.to_integer(-1));
................................................................................
    ATF_REQUIRE_EQ(0, state.get_top());
}


ATF_TEST_CASE_WITHOUT_HEAD(forget);
ATF_TEST_CASE_BODY(forget)
{
    xlua::state state;
    {
        xlua::stack_cleaner cleaner(state);
        state.push_integer(15);
        state.push_integer(30);
        cleaner.forget();
        state.push_integer(60);
        ATF_REQUIRE_EQ(3, state.get_top());
    }
    ATF_REQUIRE_EQ(2, state.get_top());

Changes to tests/state_test.cpp.

22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
..
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
..
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
...
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
...
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
...
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
...
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
...
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
...
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
...
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
...
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
...
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
...
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
...
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
...
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
...
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
...
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
...
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
...
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
...
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
...
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
...
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
...
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
...
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
...
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
...
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
...
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
...
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
...
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
....
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
....
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "xlua/state.ipp"

#include <cstring>
#include <fstream>
#include <iostream>
#include <stdexcept>

#include <atf-c++.hpp>
#include <lua.hpp>

#include "xlua/c_gate.hpp"
#include "xlua/exceptions.hpp"
#include "xlua/test_utils.hpp"


// A note about the lutok::state tests.
//
// The methods of lutok::state are, in general, thin wrappers around the
// corresponding Lua C API methods.  The tests below are simple unit tests that
// ensure that these functions just delegate the calls to the Lua library.  We
// do not intend to test the validity of the methods themselves (that's the
// job of the Lua authors).  That said, we test those conditions we rely on,
// such as the reporting of errors and the default values to the API.
//
// Lastly, for every test case that stresses a single lutok::state method, we
// only call that method directly.  All other Lua state manipulation operations
// are performed by means of direct calls to the Lua C API.  This is to ensure
// that the wrapped methods are really talking to Lua.


namespace {

................................................................................
/// Checks if a symbol is available.
///
/// \param state The Lua state.
/// \param symbol The symbol to check for.
///
/// \return True if the symbol is defined, false otherwise.
static bool
is_available(lutok::state& state, const char* symbol)
{
    luaL_loadstring(raw(state), (std::string("return ") + symbol).c_str());
    const bool ok = (lua_pcall(raw(state), 0, 1, 0) == 0 &&
                     !lua_isnil(raw(state), -1));
    lua_pop(raw(state), 1);
    std::cout << "Symbol " << symbol << (ok ? " found\n" : " not found\n");
    return ok;
................................................................................
///
/// \post The test case terminates if there is any module present when expected
/// is empty or if there two modules loaded when expected is defined.
///
/// \param state The Lua state.
/// \param expected The module to expect.  Empty if no modules are allowed.
static void
check_modules(lutok::state& state, const std::string& expected)
{
    std::cout << "Checking loaded modules" <<
        (expected.empty() ? "" : (" (" + expected + " expected)")) << "\n";
    ATF_REQUIRE(!((expected == "base") ^ (is_available(state, "assert"))));
    ATF_REQUIRE(!((expected == "string") ^
                  (is_available(state, "string.byte"))));
    ATF_REQUIRE(!((expected == "table") ^
................................................................................
///
/// \param raw_state The raw Lua state.
///
/// \return The number of result values, i.e. 2.
static int
c_get_upvalues(lua_State* raw_state)
{
    lutok::state state = lutok::state_c_gate::connect(raw_state);
    const int i1 = lua_tointeger(raw_state, state.upvalue_index(1));
    const int i2 = lua_tointeger(raw_state, state.upvalue_index(2));
    lua_pushinteger(raw_state, i1);
    lua_pushinteger(raw_state, i2);
    return 2;
}

................................................................................
/// \pre stack(-1) contains the second factor.
/// \post stack(-1) contains the product of the two input factors.
///
/// \param state The Lua state.
///
/// \return The number of result values, i.e. 1.
static int
cxx_multiply_closure(lutok::state& state)
{
    const int f1 = lua_tointeger(raw(state), lua_upvalueindex(1));
    const int f2 = lua_tointeger(raw(state), -1);
    lua_pushinteger(raw(state), f1 * f2);
    return 1;
}

................................................................................
/// \return The number of result values, i.e. 1.
///
/// \throw std::runtime_error If the divisor is zero.
/// \throw std::string If the dividend or the divisor are negative.  This is an
///     exception not derived from std::exception on purpose to ensure that the
///     C++ wrapping correctly captures any exception regardless of its type.
static int
cxx_divide(lutok::state& state)
{
    const int dividend = state.to_integer(-2);
    const int divisor = state.to_integer(-1);
    if (divisor == 0)
        throw std::runtime_error("Divisor is 0");
    if (dividend < 0 || divisor < 0)
        throw std::string("Cannot divide negative numbers");
................................................................................
/// \param state The Lua state.
///
/// \return Never returns.
///
/// \throw std::runtime_error Unconditionally, with an error message formed by
///     the repetition of 'A' as many times as requested.
static int
raise_long_error(lutok::state& state)
{
    const int length = state.to_integer(-1);
    throw std::runtime_error(std::string(length, 'A').c_str());
}


}  // anonymous namespace


ATF_TEST_CASE_WITHOUT_HEAD(close);
ATF_TEST_CASE_BODY(close)
{
    lutok::state state;
    state.close();
    // The destructor for state will run now.  If it does a second close, we may
    // crash, so let's see if we don't.
}


ATF_TEST_CASE_WITHOUT_HEAD(get_global__ok);
ATF_TEST_CASE_BODY(get_global__ok)
{
    lutok::state state;
    ATF_REQUIRE(luaL_dostring(raw(state), "test_variable = 3") == 0);
    state.get_global("test_variable");
    ATF_REQUIRE(lua_isnumber(raw(state), -1));
    lua_pop(raw(state), 1);
}


ATF_TEST_CASE_WITHOUT_HEAD(get_global__undefined);
ATF_TEST_CASE_BODY(get_global__undefined)
{
    lutok::state state;
    state.get_global("test_variable");
    ATF_REQUIRE(lua_isnil(raw(state), -1));
    lua_pop(raw(state), 1);
}


ATF_TEST_CASE_WITHOUT_HEAD(get_global_table);
ATF_TEST_CASE_BODY(get_global_table)
{
    lutok::state state;
    ATF_REQUIRE(luaL_dostring(raw(state), "global_variable = 'hello'") == 0);
    state.get_global_table();
    lua_pushstring(raw(state), "global_variable");
    lua_gettable(raw(state), -2);
    ATF_REQUIRE(lua_isstring(raw(state), -1));
    ATF_REQUIRE(std::strcmp("hello", lua_tostring(raw(state), -1)) == 0);
    lua_pop(raw(state), 2);
}


ATF_TEST_CASE_WITHOUT_HEAD(get_metafield__ok);
ATF_TEST_CASE_BODY(get_metafield__ok)
{
    lutok::state state;
    luaL_openlibs(raw(state));
    ATF_REQUIRE(luaL_dostring(raw(state), "meta = { foo = 567 }; "
                              "t = {}; setmetatable(t, meta)") == 0);
    lua_getglobal(raw(state), "t");
    ATF_REQUIRE(state.get_metafield(-1, "foo"));
    ATF_REQUIRE(lua_isnumber(raw(state), -1));
    ATF_REQUIRE_EQ(567, lua_tointeger(raw(state), -1));
................................................................................
    lua_pop(raw(state), 2);
}


ATF_TEST_CASE_WITHOUT_HEAD(get_metafield__undefined);
ATF_TEST_CASE_BODY(get_metafield__undefined)
{
    lutok::state state;
    luaL_openlibs(raw(state));
    ATF_REQUIRE(luaL_dostring(raw(state), "meta = { foo = 567 }; "
                              "t = {}; setmetatable(t, meta)") == 0);
    lua_getglobal(raw(state), "t");
    ATF_REQUIRE(!state.get_metafield(-1, "bar"));
    lua_pop(raw(state), 1);
}


ATF_TEST_CASE_WITHOUT_HEAD(get_metatable__ok);
ATF_TEST_CASE_BODY(get_metatable__ok)
{
    lutok::state state;
    luaL_openlibs(raw(state));
    ATF_REQUIRE(luaL_dostring(raw(state), "meta = { foo = 567 }; "
                              "t = {}; setmetatable(t, meta)") == 0);
    lua_getglobal(raw(state), "t");
    lua_pushinteger(raw(state), 5555);
    ATF_REQUIRE(state.get_metatable(-2));
    ATF_REQUIRE(lua_istable(raw(state), -1));
................................................................................
    lua_pop(raw(state), 4);
}


ATF_TEST_CASE_WITHOUT_HEAD(get_metatable__undefined);
ATF_TEST_CASE_BODY(get_metatable__undefined)
{
    lutok::state state;
    ATF_REQUIRE(luaL_dostring(raw(state), "t = {}") == 0);
    lua_getglobal(raw(state), "t");
    ATF_REQUIRE(!state.get_metatable(-1));
    lua_pop(raw(state), 1);
}


ATF_TEST_CASE_WITHOUT_HEAD(get_table__ok);
ATF_TEST_CASE_BODY(get_table__ok)
{
    lutok::state state;
    ATF_REQUIRE(luaL_dostring(raw(state), "t = { a = 1, bar = 234 }") == 0);
    lua_getglobal(raw(state), "t");
    lua_pushstring(raw(state), "bar");
    state.get_table(-2);
    ATF_REQUIRE(lua_isnumber(raw(state), -1));
    ATF_REQUIRE_EQ(234, lua_tointeger(raw(state), -1));
    lua_pop(raw(state), 2);
}


ATF_TEST_CASE_WITHOUT_HEAD(get_table__nil);
ATF_TEST_CASE_BODY(get_table__nil)
{
    lutok::state state;
    lua_pushnil(raw(state));
    lua_pushinteger(raw(state), 1);
    REQUIRE_API_ERROR("lua_gettable", state.get_table(-2));
    ATF_REQUIRE_EQ(2, lua_gettop(raw(state)));
    lua_pop(raw(state), 2);
}


ATF_TEST_CASE_WITHOUT_HEAD(get_table__unknown_index);
ATF_TEST_CASE_BODY(get_table__unknown_index)
{
    lutok::state state;
    ATF_REQUIRE(luaL_dostring(raw(state),
                              "the_table = { foo = 1, bar = 2 }") == 0);
    lua_getglobal(raw(state), "the_table");
    lua_pushstring(raw(state), "baz");
    state.get_table(-2);
    ATF_REQUIRE(lua_isnil(raw(state), -1));
    lua_pop(raw(state), 2);
}


ATF_TEST_CASE_WITHOUT_HEAD(get_top);
ATF_TEST_CASE_BODY(get_top)
{
    lutok::state state;
    ATF_REQUIRE_EQ(0, state.get_top());
    lua_pushinteger(raw(state), 3);
    ATF_REQUIRE_EQ(1, state.get_top());
    lua_pushinteger(raw(state), 3);
    ATF_REQUIRE_EQ(2, state.get_top());
    lua_pop(raw(state), 2);
}


ATF_TEST_CASE_WITHOUT_HEAD(insert);
ATF_TEST_CASE_BODY(insert)
{
    lutok::state state;
    lua_pushinteger(raw(state), 1);
    lua_pushinteger(raw(state), 2);
    lua_pushinteger(raw(state), 3);
    lua_pushinteger(raw(state), 4);
    state.insert(-3);
    ATF_REQUIRE_EQ(3, lua_tointeger(raw(state), -1));
    ATF_REQUIRE_EQ(2, lua_tointeger(raw(state), -2));
................................................................................
    lua_pop(raw(state), 4);
}


ATF_TEST_CASE_WITHOUT_HEAD(is_boolean__empty);
ATF_TEST_CASE_BODY(is_boolean__empty)
{
    lutok::state state;
    ATF_REQUIRE(!state.is_boolean(-1));
}


ATF_TEST_CASE_WITHOUT_HEAD(is_boolean__ok);
ATF_TEST_CASE_BODY(is_boolean__ok)
{
    lutok::state state;
    lua_pushboolean(raw(state), 1);
    ATF_REQUIRE(state.is_boolean(-1));
    lua_pushinteger(raw(state), 5);
    ATF_REQUIRE(!state.is_boolean(-1));
    ATF_REQUIRE(state.is_boolean(-2));
    lua_pop(raw(state), 2);
}


ATF_TEST_CASE_WITHOUT_HEAD(is_function__empty);
ATF_TEST_CASE_BODY(is_function__empty)
{
    lutok::state state;
    ATF_REQUIRE(!state.is_function(-1));
}


ATF_TEST_CASE_WITHOUT_HEAD(is_function__ok);
ATF_TEST_CASE_BODY(is_function__ok)
{
    lutok::state state;
    luaL_dostring(raw(state), "function my_func(a, b) return a + b; end");

    lua_getglobal(raw(state), "my_func");
    ATF_REQUIRE(state.is_function(-1));
    lua_pushinteger(raw(state), 5);
    ATF_REQUIRE(!state.is_function(-1));
    ATF_REQUIRE(state.is_function(-2));
................................................................................
    lua_pop(raw(state), 2);
}


ATF_TEST_CASE_WITHOUT_HEAD(is_nil__empty);
ATF_TEST_CASE_BODY(is_nil__empty)
{
    lutok::state state;
    ATF_REQUIRE(state.is_nil(-1));
}


ATF_TEST_CASE_WITHOUT_HEAD(is_nil__ok);
ATF_TEST_CASE_BODY(is_nil__ok)
{
    lutok::state state;
    lua_pushnil(raw(state));
    ATF_REQUIRE(state.is_nil(-1));
    lua_pushinteger(raw(state), 5);
    ATF_REQUIRE(!state.is_nil(-1));
    ATF_REQUIRE(state.is_nil(-2));
    lua_pop(raw(state), 2);
}


ATF_TEST_CASE_WITHOUT_HEAD(is_number__empty);
ATF_TEST_CASE_BODY(is_number__empty)
{
    lutok::state state;
    ATF_REQUIRE(!state.is_number(-1));
}


ATF_TEST_CASE_WITHOUT_HEAD(is_number__ok);
ATF_TEST_CASE_BODY(is_number__ok)
{
    lutok::state state;
    lua_pushnil(raw(state));
    ATF_REQUIRE(!state.is_number(-1));
    lua_pushinteger(raw(state), 5);
    ATF_REQUIRE(state.is_number(-1));
    ATF_REQUIRE(!state.is_number(-2));
    lua_pop(raw(state), 2);
}


ATF_TEST_CASE_WITHOUT_HEAD(is_string__empty);
ATF_TEST_CASE_BODY(is_string__empty)
{
    lutok::state state;
    ATF_REQUIRE(!state.is_string(-1));
}


ATF_TEST_CASE_WITHOUT_HEAD(is_string__ok);
ATF_TEST_CASE_BODY(is_string__ok)
{
    lutok::state state;
    lua_pushinteger(raw(state), 3);
    ATF_REQUIRE(state.is_string(-1));
    lua_pushnil(raw(state));
    ATF_REQUIRE(!state.is_string(-1));
    ATF_REQUIRE(state.is_string(-2));
    lua_pushstring(raw(state), "foo");
    ATF_REQUIRE(state.is_string(-1));
................................................................................
    lua_pop(raw(state), 3);
}


ATF_TEST_CASE_WITHOUT_HEAD(is_table__empty);
ATF_TEST_CASE_BODY(is_table__empty)
{
    lutok::state state;
    ATF_REQUIRE(!state.is_table(-1));
}


ATF_TEST_CASE_WITHOUT_HEAD(is_table__ok);
ATF_TEST_CASE_BODY(is_table__ok)
{
    lutok::state state;
    luaL_dostring(raw(state), "t = {3, 4, 5}");

    lua_pushstring(raw(state), "foo");
    ATF_REQUIRE(!state.is_table(-1));
    lua_getglobal(raw(state), "t");
    ATF_REQUIRE(state.is_table(-1));
    ATF_REQUIRE(!state.is_table(-2));
................................................................................
    lua_pop(raw(state), 2);
}


ATF_TEST_CASE_WITHOUT_HEAD(is_userdata__empty);
ATF_TEST_CASE_BODY(is_userdata__empty)
{
    lutok::state state;
    ATF_REQUIRE(!state.is_userdata(-1));
}


ATF_TEST_CASE_WITHOUT_HEAD(is_userdata__ok);
ATF_TEST_CASE_BODY(is_userdata__ok)
{
    lutok::state state;

    lua_pushstring(raw(state), "foo");
    ATF_REQUIRE(!state.is_userdata(-1));
    lua_newuserdata(raw(state), 543);
    ATF_REQUIRE(state.is_userdata(-1));
    ATF_REQUIRE(!state.is_userdata(-2));
    lua_pop(raw(state), 2);
................................................................................
ATF_TEST_CASE_WITHOUT_HEAD(load_file__ok);
ATF_TEST_CASE_BODY(load_file__ok)
{
    std::ofstream output("test.lua");
    output << "in_the_file = \"oh yes\"\n";
    output.close();

    lutok::state state;
    state.load_file("test.lua");
    ATF_REQUIRE(lua_pcall(raw(state), 0, 0, 0) == 0);
    lua_getglobal(raw(state), "in_the_file");
    ATF_REQUIRE(std::strcmp("oh yes", lua_tostring(raw(state), -1)) == 0);
    lua_pop(raw(state), 1);
}

................................................................................
ATF_TEST_CASE_WITHOUT_HEAD(load_file__api_error);
ATF_TEST_CASE_BODY(load_file__api_error)
{
    std::ofstream output("test.lua");
    output << "I have a bad syntax!  Wohoo!\n";
    output.close();

    lutok::state state;
    REQUIRE_API_ERROR("luaL_loadfile", state.load_file("test.lua"));
}


ATF_TEST_CASE_WITHOUT_HEAD(load_file__file_not_found_error);
ATF_TEST_CASE_BODY(load_file__file_not_found_error)
{
    lutok::state state;
    ATF_REQUIRE_THROW_RE(lutok::file_not_found_error, "missing.lua",
                         state.load_file("missing.lua"));
}


ATF_TEST_CASE_WITHOUT_HEAD(load_string__ok);
ATF_TEST_CASE_BODY(load_string__ok)
{
    lutok::state state;
    state.load_string("return 2 + 3");
    ATF_REQUIRE(lua_pcall(raw(state), 0, 1, 0) == 0);
    ATF_REQUIRE_EQ(5, lua_tointeger(raw(state), -1));
    lua_pop(raw(state), 1);
}


ATF_TEST_CASE_WITHOUT_HEAD(load_string__fail);
ATF_TEST_CASE_BODY(load_string__fail)
{
    lutok::state state;
    REQUIRE_API_ERROR("luaL_loadstring", state.load_string("-"));
}


ATF_TEST_CASE_WITHOUT_HEAD(new_table);
ATF_TEST_CASE_BODY(new_table)
{
    lutok::state state;
    state.new_table();
    ATF_REQUIRE_EQ(1, lua_gettop(raw(state)));
    ATF_REQUIRE(lua_istable(raw(state), -1));
    lua_pop(raw(state), 1);
}


ATF_TEST_CASE_WITHOUT_HEAD(new_userdata);
ATF_TEST_CASE_BODY(new_userdata)
{
    lutok::state state;
    int* pointer = state.new_userdata< int >();
    *pointer = 1234;
    ATF_REQUIRE_EQ(1, lua_gettop(raw(state)));
    ATF_REQUIRE(lua_isuserdata(raw(state), -1));
    lua_pop(raw(state), 1);
}


ATF_TEST_CASE_WITHOUT_HEAD(next__empty);
ATF_TEST_CASE_BODY(next__empty)
{
    lutok::state state;
    luaL_dostring(raw(state), "t = {}");

    lua_getglobal(raw(state), "t");
    lua_pushstring(raw(state), "this is a dummy value");
    lua_pushnil(raw(state));
    ATF_REQUIRE(!state.next(-3));
    lua_pop(raw(state), 2);
}


ATF_TEST_CASE_WITHOUT_HEAD(next__many);
ATF_TEST_CASE_BODY(next__many)
{
    lutok::state state;
    luaL_dostring(raw(state), "t = {}; t[1] = 100; t[2] = 200");

    lua_getglobal(raw(state), "t");
    lua_pushnil(raw(state));

    ATF_REQUIRE(state.next(-2));
    ATF_REQUIRE_EQ(3, lua_gettop(raw(state)));
................................................................................
    lua_pop(raw(state), 1);
}


ATF_TEST_CASE_WITHOUT_HEAD(open_base);
ATF_TEST_CASE_BODY(open_base)
{
    lutok::state state;
    check_modules(state, "");
    state.open_base();
    check_modules(state, "base");
}


ATF_TEST_CASE_WITHOUT_HEAD(open_all);
ATF_TEST_CASE_BODY(open_all)
{
    lutok::state state;
    check_modules(state, "");
    state.open_all();
    // Best-effort attempt at looking for a bunch of possible modules.
    ATF_REQUIRE(is_available(state, "assert"));
    ATF_REQUIRE(is_available(state, "debug.getinfo"));
    ATF_REQUIRE(is_available(state, "package.path"));
    ATF_REQUIRE(is_available(state, "string.byte"));
................................................................................
    ATF_REQUIRE(is_available(state, "table.concat"));
}


ATF_TEST_CASE_WITHOUT_HEAD(open_string);
ATF_TEST_CASE_BODY(open_string)
{
    lutok::state state;
    check_modules(state, "");
    state.open_string();
    check_modules(state, "string");
}


ATF_TEST_CASE_WITHOUT_HEAD(open_table);
ATF_TEST_CASE_BODY(open_table)
{
    lutok::state state;
    check_modules(state, "");
    state.open_table();
    check_modules(state, "table");
}


ATF_TEST_CASE_WITHOUT_HEAD(pcall__ok);
ATF_TEST_CASE_BODY(pcall__ok)
{
    lutok::state state;
    luaL_loadstring(raw(state), "function mul(a, b) return a * b; end");
    state.pcall(0, 0, 0);
    state.get_global_table();
    lua_pushstring(raw(state), "mul");
    lua_gettable(raw(state), -2);
    lua_pushinteger(raw(state), 3);
    lua_pushinteger(raw(state), 5);
................................................................................
    lua_pop(raw(state), 2);
}


ATF_TEST_CASE_WITHOUT_HEAD(pcall__fail);
ATF_TEST_CASE_BODY(pcall__fail)
{
    lutok::state state;
    lua_pushnil(raw(state));
    REQUIRE_API_ERROR("lua_pcall", state.pcall(0, 0, 0));
}


ATF_TEST_CASE_WITHOUT_HEAD(pop__one);
ATF_TEST_CASE_BODY(pop__one)
{
    lutok::state state;
    lua_pushinteger(raw(state), 10);
    lua_pushinteger(raw(state), 20);
    lua_pushinteger(raw(state), 30);
    state.pop(1);
    ATF_REQUIRE_EQ(2, lua_gettop(raw(state)));
    ATF_REQUIRE_EQ(20, lua_tointeger(raw(state), -1));
    lua_pop(raw(state), 2);
}


ATF_TEST_CASE_WITHOUT_HEAD(pop__many);
ATF_TEST_CASE_BODY(pop__many)
{
    lutok::state state;
    lua_pushinteger(raw(state), 10);
    lua_pushinteger(raw(state), 20);
    lua_pushinteger(raw(state), 30);
    state.pop(2);
    ATF_REQUIRE_EQ(1, lua_gettop(raw(state)));
    ATF_REQUIRE_EQ(10, lua_tointeger(raw(state), -1));
    lua_pop(raw(state), 1);
}


ATF_TEST_CASE_WITHOUT_HEAD(push_boolean);
ATF_TEST_CASE_BODY(push_boolean)
{
    lutok::state state;
    state.push_boolean(true);
    ATF_REQUIRE_EQ(1, lua_gettop(raw(state)));
    ATF_REQUIRE(lua_toboolean(raw(state), -1));
    state.push_boolean(false);
    ATF_REQUIRE_EQ(2, lua_gettop(raw(state)));
    ATF_REQUIRE(!lua_toboolean(raw(state), -1));
    ATF_REQUIRE(lua_toboolean(raw(state), -2));
................................................................................
    lua_pop(raw(state), 2);
}


ATF_TEST_CASE_WITHOUT_HEAD(push_cxx_closure);
ATF_TEST_CASE_BODY(push_cxx_closure)
{
    lutok::state state;
    state.push_integer(15);
    state.push_cxx_closure(cxx_multiply_closure, 1);
    lua_setglobal(raw(state), "cxx_multiply_closure");

    ATF_REQUIRE(luaL_dostring(raw(state),
                              "return cxx_multiply_closure(10)") == 0);
    ATF_REQUIRE_EQ(150, lua_tointeger(raw(state), -1));
................................................................................
    lua_pop(raw(state), 1);
}


ATF_TEST_CASE_WITHOUT_HEAD(push_cxx_function__ok);
ATF_TEST_CASE_BODY(push_cxx_function__ok)
{
    lutok::state state;
    state.push_cxx_function(cxx_divide);
    lua_setglobal(raw(state), "cxx_divide");

    ATF_REQUIRE(luaL_dostring(raw(state), "return cxx_divide(17, 3)") == 0);
    ATF_REQUIRE_EQ(5, lua_tointeger(raw(state), -2));
    ATF_REQUIRE_EQ(2, lua_tointeger(raw(state), -1));
    lua_pop(raw(state), 2);
}


ATF_TEST_CASE_WITHOUT_HEAD(push_cxx_function__fail_exception);
ATF_TEST_CASE_BODY(push_cxx_function__fail_exception)
{
    lutok::state state;
    state.push_cxx_function(cxx_divide);
    lua_setglobal(raw(state), "cxx_divide");

    ATF_REQUIRE(luaL_dostring(raw(state), "return cxx_divide(15, 0)") != 0);
    ATF_REQUIRE_MATCH("Divisor is 0", lua_tostring(raw(state), -1));
    lua_pop(raw(state), 1);
}


ATF_TEST_CASE_WITHOUT_HEAD(push_cxx_function__fail_anything);
ATF_TEST_CASE_BODY(push_cxx_function__fail_anything)
{
    lutok::state state;
    state.push_cxx_function(cxx_divide);
    lua_setglobal(raw(state), "cxx_divide");

    ATF_REQUIRE(luaL_dostring(raw(state), "return cxx_divide(-3, -1)") != 0);
    ATF_REQUIRE_MATCH("Unhandled exception", lua_tostring(raw(state), -1));
    lua_pop(raw(state), 1);
}


ATF_TEST_CASE_WITHOUT_HEAD(push_cxx_function__fail_overflow);
ATF_TEST_CASE_BODY(push_cxx_function__fail_overflow)
{
    lutok::state state;
    state.push_cxx_function(raise_long_error);
    lua_setglobal(raw(state), "fail");

    ATF_REQUIRE(luaL_dostring(raw(state), "return fail(900)") != 0);
    ATF_REQUIRE_MATCH(std::string(900, 'A'), lua_tostring(raw(state), -1));
    lua_pop(raw(state), 1);

................................................................................
    lua_pop(raw(state), 1);
}


ATF_TEST_CASE_WITHOUT_HEAD(push_integer);
ATF_TEST_CASE_BODY(push_integer)
{
    lutok::state state;
    state.push_integer(12);
    ATF_REQUIRE_EQ(1, lua_gettop(raw(state)));
    ATF_REQUIRE_EQ(12, lua_tointeger(raw(state), -1));
    state.push_integer(34);
    ATF_REQUIRE_EQ(2, lua_gettop(raw(state)));
    ATF_REQUIRE_EQ(34, lua_tointeger(raw(state), -1));
    ATF_REQUIRE_EQ(12, lua_tointeger(raw(state), -2));
................................................................................
    lua_pop(raw(state), 2);
}


ATF_TEST_CASE_WITHOUT_HEAD(push_nil);
ATF_TEST_CASE_BODY(push_nil)
{
    lutok::state state;
    state.push_nil();
    ATF_REQUIRE_EQ(1, lua_gettop(raw(state)));
    ATF_REQUIRE(lua_isnil(raw(state), -1));
    state.push_integer(34);
    ATF_REQUIRE_EQ(2, lua_gettop(raw(state)));
    ATF_REQUIRE(!lua_isnil(raw(state), -1));
    ATF_REQUIRE(lua_isnil(raw(state), -2));
................................................................................
    lua_pop(raw(state), 2);
}


ATF_TEST_CASE_WITHOUT_HEAD(push_string);
ATF_TEST_CASE_BODY(push_string)
{
    lutok::state state;

    {
        std::string str = "first";
        state.push_string(str);
        ATF_REQUIRE_EQ(1, lua_gettop(raw(state)));
        ATF_REQUIRE_EQ(std::string("first"), lua_tostring(raw(state), -1));
        str = "second";
................................................................................
    lua_pop(raw(state), 2);
}


ATF_TEST_CASE_WITHOUT_HEAD(push_value);
ATF_TEST_CASE_BODY(push_value)
{
    lutok::state state;

    lua_pushinteger(raw(state), 10);
    lua_pushinteger(raw(state), 20);
    state.push_value(-2);
    ATF_REQUIRE_EQ(3, lua_gettop(raw(state)));
    ATF_REQUIRE_EQ(10, lua_tointeger(raw(state), -1));
    ATF_REQUIRE_EQ(20, lua_tointeger(raw(state), -2));
................................................................................
    lua_pop(raw(state), 3);
}


ATF_TEST_CASE_WITHOUT_HEAD(raw_get);
ATF_TEST_CASE_BODY(raw_get)
{
    lutok::state state;

    luaL_openlibs(raw(state));
    ATF_REQUIRE(luaL_dostring(
        raw(state), "t = {foo=123} ; setmetatable(t, {__index=1})") == 0);
    lua_getglobal(raw(state), "t");
    lua_pushinteger(raw(state), 9876);
    lua_pushstring(raw(state), "foo");
................................................................................
    lua_pop(raw(state), 3);
}


ATF_TEST_CASE_WITHOUT_HEAD(raw_set);
ATF_TEST_CASE_BODY(raw_set)
{
    lutok::state state;

    luaL_openlibs(raw(state));
    ATF_REQUIRE(luaL_dostring(
        raw(state), "t = {} ; setmetatable(t, {__newindex=1})") == 0);
    lua_getglobal(raw(state), "t");
    lua_pushinteger(raw(state), 876);
    lua_pushstring(raw(state), "foo");
................................................................................
    lua_pop(raw(state), 3);
}


ATF_TEST_CASE_WITHOUT_HEAD(registry_index);
ATF_TEST_CASE_BODY(registry_index)
{
    lutok::state state;
    lua_pushvalue(raw(state), lutok::registry_index);
    lua_pushstring(raw(state), "custom_variable");
    lua_pushstring(raw(state), "custom value");
    lua_settable(raw(state), -3);
    lua_pop(raw(state), 1);
    ATF_REQUIRE(luaL_dostring(raw(state),
                              "return custom_variable == nil") == 0);
    ATF_REQUIRE(lua_isboolean(raw(state), -1));
................................................................................
    lua_pop(raw(state), 1);
}


ATF_TEST_CASE_WITHOUT_HEAD(set_global);
ATF_TEST_CASE_BODY(set_global)
{
    lutok::state state;
    lua_pushinteger(raw(state), 3);
    state.set_global("test_variable");
    ATF_REQUIRE(luaL_dostring(raw(state), "return test_variable + 1") == 0);
    ATF_REQUIRE(lua_isnumber(raw(state), -1));
    ATF_REQUIRE_EQ(4, lua_tointeger(raw(state), -1));
    lua_pop(raw(state), 1);
}


ATF_TEST_CASE_WITHOUT_HEAD(set_metatable);
ATF_TEST_CASE_BODY(set_metatable)
{
    lutok::state state;
    ATF_REQUIRE(luaL_dostring(
        raw(state),
        "mt = {}\n"
        "mt.__add = function(a, b) return a[1] + b end\n"
        "numbers = {}\n"
        "numbers[1] = 5\n") == 0);

................................................................................
    lua_pop(raw(state), 1);
}


ATF_TEST_CASE_WITHOUT_HEAD(set_table__ok);
ATF_TEST_CASE_BODY(set_table__ok)
{
    lutok::state state;
    ATF_REQUIRE(luaL_dostring(raw(state), "t = { a = 1, bar = 234 }") == 0);
    lua_getglobal(raw(state), "t");

    lua_pushstring(raw(state), "bar");
    lua_pushstring(raw(state), "baz");
    state.set_table(-3);
    ATF_REQUIRE_EQ(1, lua_gettop(raw(state)));
................................................................................
    lua_pop(raw(state), 1);
}


ATF_TEST_CASE_WITHOUT_HEAD(set_table__nil);
ATF_TEST_CASE_BODY(set_table__nil)
{
    lutok::state state;
    lua_pushnil(raw(state));
    lua_pushinteger(raw(state), 1);
    lua_pushinteger(raw(state), 2);
    REQUIRE_API_ERROR("lua_settable", state.set_table(-3));
    lua_pop(raw(state), 3);
}


ATF_TEST_CASE_WITHOUT_HEAD(to_boolean);
ATF_TEST_CASE_BODY(to_boolean)
{
    lutok::state state;
    lua_pushboolean(raw(state), 0);
    lua_pushboolean(raw(state), 1);
    ATF_REQUIRE(!state.to_boolean(-2));
    ATF_REQUIRE(state.to_boolean(-1));
    lua_pop(raw(state), 2);
}


ATF_TEST_CASE_WITHOUT_HEAD(to_integer);
ATF_TEST_CASE_BODY(to_integer)
{
    lutok::state state;
    lua_pushinteger(raw(state), 12);
    lua_pushstring(raw(state), "foobar");
    ATF_REQUIRE_EQ(12, state.to_integer(-2));
    lua_pop(raw(state), 2);
}


ATF_TEST_CASE_WITHOUT_HEAD(to_string);
ATF_TEST_CASE_BODY(to_string)
{
    lutok::state state;
    lua_pushstring(raw(state), "foobar");
    lua_pushinteger(raw(state), 12);
    ATF_REQUIRE_EQ("foobar", state.to_string(-2));
    ATF_REQUIRE_EQ("12", state.to_string(-1));
    lua_pop(raw(state), 2);
}


ATF_TEST_CASE_WITHOUT_HEAD(to_userdata);
ATF_TEST_CASE_BODY(to_userdata)
{
    lutok::state state;
    {
        int* pointer = static_cast< int* >(
            lua_newuserdata(raw(state), sizeof(int)));
        *pointer = 987;
    }

    lua_pushinteger(raw(state), 3);
................................................................................
    lua_pop(raw(state), 2);
}


ATF_TEST_CASE_WITHOUT_HEAD(upvalue_index);
ATF_TEST_CASE_BODY(upvalue_index)
{
    lutok::state state;
    lua_pushinteger(raw(state), 25);
    lua_pushinteger(raw(state), 30);
    lua_pushcclosure(raw(state), c_get_upvalues, 2);
    lua_setglobal(raw(state), "c_get_upvalues");

    ATF_REQUIRE(luaL_dostring(raw(state),
                              "return c_get_upvalues()") == 0);







|









|
|
|


|

|






|







 







|







 







|







 







|







 







|







 







|







 







|












|









|










|









|













|







 







|












|







 







|










|













|











|













|












|







 







|







|












|







|







 







|







|












|







|












|







|







 







|







|







 







|







|







 







|







 







|







|
|







|










|







|










|











|













|







 







|









|







 







|









|









|







 







|








|













|













|







 







|







 







|













|












|












|







 







|







 







|







 







|







 







|







 







|







 







|







 







|
|







 







|












|







 







|







 







|











|











|










|











|







 







|







22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
..
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
..
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
...
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
...
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
...
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
...
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
...
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
...
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
...
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
...
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
...
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
...
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
...
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
...
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
...
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
...
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
...
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
...
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
...
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
...
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
...
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
...
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
...
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
...
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
...
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
...
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
...
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
...
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
....
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
....
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include <xlua/state.ipp>

#include <cstring>
#include <fstream>
#include <iostream>
#include <stdexcept>

#include <atf-c++.hpp>
#include <lua.hpp>

#include <xlua/c_gate.hpp>
#include <xlua/exceptions.hpp>
#include <xlua/test_utils.hpp>


// A note about the xlua::state tests.
//
// The methods of xlua::state are, in general, thin wrappers around the
// corresponding Lua C API methods.  The tests below are simple unit tests that
// ensure that these functions just delegate the calls to the Lua library.  We
// do not intend to test the validity of the methods themselves (that's the
// job of the Lua authors).  That said, we test those conditions we rely on,
// such as the reporting of errors and the default values to the API.
//
// Lastly, for every test case that stresses a single xlua::state method, we
// only call that method directly.  All other Lua state manipulation operations
// are performed by means of direct calls to the Lua C API.  This is to ensure
// that the wrapped methods are really talking to Lua.


namespace {

................................................................................
/// Checks if a symbol is available.
///
/// \param state The Lua state.
/// \param symbol The symbol to check for.
///
/// \return True if the symbol is defined, false otherwise.
static bool
is_available(xlua::state& state, const char* symbol)
{
    luaL_loadstring(raw(state), (std::string("return ") + symbol).c_str());
    const bool ok = (lua_pcall(raw(state), 0, 1, 0) == 0 &&
                     !lua_isnil(raw(state), -1));
    lua_pop(raw(state), 1);
    std::cout << "Symbol " << symbol << (ok ? " found\n" : " not found\n");
    return ok;
................................................................................
///
/// \post The test case terminates if there is any module present when expected
/// is empty or if there two modules loaded when expected is defined.
///
/// \param state The Lua state.
/// \param expected The module to expect.  Empty if no modules are allowed.
static void
check_modules(xlua::state& state, const std::string& expected)
{
    std::cout << "Checking loaded modules" <<
        (expected.empty() ? "" : (" (" + expected + " expected)")) << "\n";
    ATF_REQUIRE(!((expected == "base") ^ (is_available(state, "assert"))));
    ATF_REQUIRE(!((expected == "string") ^
                  (is_available(state, "string.byte"))));
    ATF_REQUIRE(!((expected == "table") ^
................................................................................
///
/// \param raw_state The raw Lua state.
///
/// \return The number of result values, i.e. 2.
static int
c_get_upvalues(lua_State* raw_state)
{
    xlua::state state = xlua::state_c_gate::connect(raw_state);
    const int i1 = lua_tointeger(raw_state, state.upvalue_index(1));
    const int i2 = lua_tointeger(raw_state, state.upvalue_index(2));
    lua_pushinteger(raw_state, i1);
    lua_pushinteger(raw_state, i2);
    return 2;
}

................................................................................
/// \pre stack(-1) contains the second factor.
/// \post stack(-1) contains the product of the two input factors.
///
/// \param state The Lua state.
///
/// \return The number of result values, i.e. 1.
static int
cxx_multiply_closure(xlua::state& state)
{
    const int f1 = lua_tointeger(raw(state), lua_upvalueindex(1));
    const int f2 = lua_tointeger(raw(state), -1);
    lua_pushinteger(raw(state), f1 * f2);
    return 1;
}

................................................................................
/// \return The number of result values, i.e. 1.
///
/// \throw std::runtime_error If the divisor is zero.
/// \throw std::string If the dividend or the divisor are negative.  This is an
///     exception not derived from std::exception on purpose to ensure that the
///     C++ wrapping correctly captures any exception regardless of its type.
static int
cxx_divide(xlua::state& state)
{
    const int dividend = state.to_integer(-2);
    const int divisor = state.to_integer(-1);
    if (divisor == 0)
        throw std::runtime_error("Divisor is 0");
    if (dividend < 0 || divisor < 0)
        throw std::string("Cannot divide negative numbers");
................................................................................
/// \param state The Lua state.
///
/// \return Never returns.
///
/// \throw std::runtime_error Unconditionally, with an error message formed by
///     the repetition of 'A' as many times as requested.
static int
raise_long_error(xlua::state& state)
{
    const int length = state.to_integer(-1);
    throw std::runtime_error(std::string(length, 'A').c_str());
}


}  // anonymous namespace


ATF_TEST_CASE_WITHOUT_HEAD(close);
ATF_TEST_CASE_BODY(close)
{
    xlua::state state;
    state.close();
    // The destructor for state will run now.  If it does a second close, we may
    // crash, so let's see if we don't.
}


ATF_TEST_CASE_WITHOUT_HEAD(get_global__ok);
ATF_TEST_CASE_BODY(get_global__ok)
{
    xlua::state state;
    ATF_REQUIRE(luaL_dostring(raw(state), "test_variable = 3") == 0);
    state.get_global("test_variable");
    ATF_REQUIRE(lua_isnumber(raw(state), -1));
    lua_pop(raw(state), 1);
}


ATF_TEST_CASE_WITHOUT_HEAD(get_global__undefined);
ATF_TEST_CASE_BODY(get_global__undefined)
{
    xlua::state state;
    state.get_global("test_variable");
    ATF_REQUIRE(lua_isnil(raw(state), -1));
    lua_pop(raw(state), 1);
}


ATF_TEST_CASE_WITHOUT_HEAD(get_global_table);
ATF_TEST_CASE_BODY(get_global_table)
{
    xlua::state state;
    ATF_REQUIRE(luaL_dostring(raw(state), "global_variable = 'hello'") == 0);
    state.get_global_table();
    lua_pushstring(raw(state), "global_variable");
    lua_gettable(raw(state), -2);
    ATF_REQUIRE(lua_isstring(raw(state), -1));
    ATF_REQUIRE(std::strcmp("hello", lua_tostring(raw(state), -1)) == 0);
    lua_pop(raw(state), 2);
}


ATF_TEST_CASE_WITHOUT_HEAD(get_metafield__ok);
ATF_TEST_CASE_BODY(get_metafield__ok)
{
    xlua::state state;
    luaL_openlibs(raw(state));
    ATF_REQUIRE(luaL_dostring(raw(state), "meta = { foo = 567 }; "
                              "t = {}; setmetatable(t, meta)") == 0);
    lua_getglobal(raw(state), "t");
    ATF_REQUIRE(state.get_metafield(-1, "foo"));
    ATF_REQUIRE(lua_isnumber(raw(state), -1));
    ATF_REQUIRE_EQ(567, lua_tointeger(raw(state), -1));
................................................................................
    lua_pop(raw(state), 2);
}


ATF_TEST_CASE_WITHOUT_HEAD(get_metafield__undefined);
ATF_TEST_CASE_BODY(get_metafield__undefined)
{
    xlua::state state;
    luaL_openlibs(raw(state));
    ATF_REQUIRE(luaL_dostring(raw(state), "meta = { foo = 567 }; "
                              "t = {}; setmetatable(t, meta)") == 0);
    lua_getglobal(raw(state), "t");
    ATF_REQUIRE(!state.get_metafield(-1, "bar"));
    lua_pop(raw(state), 1);
}


ATF_TEST_CASE_WITHOUT_HEAD(get_metatable__ok);
ATF_TEST_CASE_BODY(get_metatable__ok)
{
    xlua::state state;
    luaL_openlibs(raw(state));
    ATF_REQUIRE(luaL_dostring(raw(state), "meta = { foo = 567 }; "
                              "t = {}; setmetatable(t, meta)") == 0);
    lua_getglobal(raw(state), "t");
    lua_pushinteger(raw(state), 5555);
    ATF_REQUIRE(state.get_metatable(-2));
    ATF_REQUIRE(lua_istable(raw(state), -1));
................................................................................
    lua_pop(raw(state), 4);
}


ATF_TEST_CASE_WITHOUT_HEAD(get_metatable__undefined);
ATF_TEST_CASE_BODY(get_metatable__undefined)
{
    xlua::state state;
    ATF_REQUIRE(luaL_dostring(raw(state), "t = {}") == 0);
    lua_getglobal(raw(state), "t");
    ATF_REQUIRE(!state.get_metatable(-1));
    lua_pop(raw(state), 1);
}


ATF_TEST_CASE_WITHOUT_HEAD(get_table__ok);
ATF_TEST_CASE_BODY(get_table__ok)
{
    xlua::state state;
    ATF_REQUIRE(luaL_dostring(raw(state), "t = { a = 1, bar = 234 }") == 0);
    lua_getglobal(raw(state), "t");
    lua_pushstring(raw(state), "bar");
    state.get_table(-2);
    ATF_REQUIRE(lua_isnumber(raw(state), -1));
    ATF_REQUIRE_EQ(234, lua_tointeger(raw(state), -1));
    lua_pop(raw(state), 2);
}


ATF_TEST_CASE_WITHOUT_HEAD(get_table__nil);
ATF_TEST_CASE_BODY(get_table__nil)
{
    xlua::state state;
    lua_pushnil(raw(state));
    lua_pushinteger(raw(state), 1);
    REQUIRE_API_ERROR("lua_gettable", state.get_table(-2));
    ATF_REQUIRE_EQ(2, lua_gettop(raw(state)));
    lua_pop(raw(state), 2);
}


ATF_TEST_CASE_WITHOUT_HEAD(get_table__unknown_index);
ATF_TEST_CASE_BODY(get_table__unknown_index)
{
    xlua::state state;
    ATF_REQUIRE(luaL_dostring(raw(state),
                              "the_table = { foo = 1, bar = 2 }") == 0);
    lua_getglobal(raw(state), "the_table");
    lua_pushstring(raw(state), "baz");
    state.get_table(-2);
    ATF_REQUIRE(lua_isnil(raw(state), -1));
    lua_pop(raw(state), 2);
}


ATF_TEST_CASE_WITHOUT_HEAD(get_top);
ATF_TEST_CASE_BODY(get_top)
{
    xlua::state state;
    ATF_REQUIRE_EQ(0, state.get_top());
    lua_pushinteger(raw(state), 3);
    ATF_REQUIRE_EQ(1, state.get_top());
    lua_pushinteger(raw(state), 3);
    ATF_REQUIRE_EQ(2, state.get_top());
    lua_pop(raw(state), 2);
}


ATF_TEST_CASE_WITHOUT_HEAD(insert);
ATF_TEST_CASE_BODY(insert)
{
    xlua::state state;
    lua_pushinteger(raw(state), 1);
    lua_pushinteger(raw(state), 2);
    lua_pushinteger(raw(state), 3);
    lua_pushinteger(raw(state), 4);
    state.insert(-3);
    ATF_REQUIRE_EQ(3, lua_tointeger(raw(state), -1));
    ATF_REQUIRE_EQ(2, lua_tointeger(raw(state), -2));
................................................................................
    lua_pop(raw(state), 4);
}


ATF_TEST_CASE_WITHOUT_HEAD(is_boolean__empty);
ATF_TEST_CASE_BODY(is_boolean__empty)
{
    xlua::state state;
    ATF_REQUIRE(!state.is_boolean(-1));
}


ATF_TEST_CASE_WITHOUT_HEAD(is_boolean__ok);
ATF_TEST_CASE_BODY(is_boolean__ok)
{
    xlua::state state;
    lua_pushboolean(raw(state), 1);
    ATF_REQUIRE(state.is_boolean(-1));
    lua_pushinteger(raw(state), 5);
    ATF_REQUIRE(!state.is_boolean(-1));
    ATF_REQUIRE(state.is_boolean(-2));
    lua_pop(raw(state), 2);
}


ATF_TEST_CASE_WITHOUT_HEAD(is_function__empty);
ATF_TEST_CASE_BODY(is_function__empty)
{
    xlua::state state;
    ATF_REQUIRE(!state.is_function(-1));
}


ATF_TEST_CASE_WITHOUT_HEAD(is_function__ok);
ATF_TEST_CASE_BODY(is_function__ok)
{
    xlua::state state;
    luaL_dostring(raw(state), "function my_func(a, b) return a + b; end");

    lua_getglobal(raw(state), "my_func");
    ATF_REQUIRE(state.is_function(-1));
    lua_pushinteger(raw(state), 5);
    ATF_REQUIRE(!state.is_function(-1));
    ATF_REQUIRE(state.is_function(-2));
................................................................................
    lua_pop(raw(state), 2);
}


ATF_TEST_CASE_WITHOUT_HEAD(is_nil__empty);
ATF_TEST_CASE_BODY(is_nil__empty)
{
    xlua::state state;
    ATF_REQUIRE(state.is_nil(-1));
}


ATF_TEST_CASE_WITHOUT_HEAD(is_nil__ok);
ATF_TEST_CASE_BODY(is_nil__ok)
{
    xlua::state state;
    lua_pushnil(raw(state));
    ATF_REQUIRE(state.is_nil(-1));
    lua_pushinteger(raw(state), 5);
    ATF_REQUIRE(!state.is_nil(-1));
    ATF_REQUIRE(state.is_nil(-2));
    lua_pop(raw(state), 2);
}


ATF_TEST_CASE_WITHOUT_HEAD(is_number__empty);
ATF_TEST_CASE_BODY(is_number__empty)
{
    xlua::state state;
    ATF_REQUIRE(!state.is_number(-1));
}


ATF_TEST_CASE_WITHOUT_HEAD(is_number__ok);
ATF_TEST_CASE_BODY(is_number__ok)
{
    xlua::state state;
    lua_pushnil(raw(state));
    ATF_REQUIRE(!state.is_number(-1));
    lua_pushinteger(raw(state), 5);
    ATF_REQUIRE(state.is_number(-1));
    ATF_REQUIRE(!state.is_number(-2));
    lua_pop(raw(state), 2);
}


ATF_TEST_CASE_WITHOUT_HEAD(is_string__empty);
ATF_TEST_CASE_BODY(is_string__empty)
{
    xlua::state state;
    ATF_REQUIRE(!state.is_string(-1));
}


ATF_TEST_CASE_WITHOUT_HEAD(is_string__ok);
ATF_TEST_CASE_BODY(is_string__ok)
{
    xlua::state state;
    lua_pushinteger(raw(state), 3);
    ATF_REQUIRE(state.is_string(-1));
    lua_pushnil(raw(state));
    ATF_REQUIRE(!state.is_string(-1));
    ATF_REQUIRE(state.is_string(-2));
    lua_pushstring(raw(state), "foo");
    ATF_REQUIRE(state.is_string(-1));
................................................................................
    lua_pop(raw(state), 3);
}


ATF_TEST_CASE_WITHOUT_HEAD(is_table__empty);
ATF_TEST_CASE_BODY(is_table__empty)
{
    xlua::state state;
    ATF_REQUIRE(!state.is_table(-1));
}


ATF_TEST_CASE_WITHOUT_HEAD(is_table__ok);
ATF_TEST_CASE_BODY(is_table__ok)
{
    xlua::state state;
    luaL_dostring(raw(state), "t = {3, 4, 5}");

    lua_pushstring(raw(state), "foo");
    ATF_REQUIRE(!state.is_table(-1));
    lua_getglobal(raw(state), "t");
    ATF_REQUIRE(state.is_table(-1));
    ATF_REQUIRE(!state.is_table(-2));
................................................................................
    lua_pop(raw(state), 2);
}


ATF_TEST_CASE_WITHOUT_HEAD(is_userdata__empty);
ATF_TEST_CASE_BODY(is_userdata__empty)
{
    xlua::state state;
    ATF_REQUIRE(!state.is_userdata(-1));
}


ATF_TEST_CASE_WITHOUT_HEAD(is_userdata__ok);
ATF_TEST_CASE_BODY(is_userdata__ok)
{
    xlua::state state;

    lua_pushstring(raw(state), "foo");
    ATF_REQUIRE(!state.is_userdata(-1));
    lua_newuserdata(raw(state), 543);
    ATF_REQUIRE(state.is_userdata(-1));
    ATF_REQUIRE(!state.is_userdata(-2));
    lua_pop(raw(state), 2);
................................................................................
ATF_TEST_CASE_WITHOUT_HEAD(load_file__ok);
ATF_TEST_CASE_BODY(load_file__ok)
{
    std::ofstream output("test.lua");
    output << "in_the_file = \"oh yes\"\n";
    output.close();

    xlua::state state;
    state.load_file("test.lua");
    ATF_REQUIRE(lua_pcall(raw(state), 0, 0, 0) == 0);
    lua_getglobal(raw(state), "in_the_file");
    ATF_REQUIRE(std::strcmp("oh yes", lua_tostring(raw(state), -1)) == 0);
    lua_pop(raw(state), 1);
}

................................................................................
ATF_TEST_CASE_WITHOUT_HEAD(load_file__api_error);
ATF_TEST_CASE_BODY(load_file__api_error)
{
    std::ofstream output("test.lua");
    output << "I have a bad syntax!  Wohoo!\n";
    output.close();

    xlua::state state;
    REQUIRE_API_ERROR("luaL_loadfile", state.load_file("test.lua"));
}


ATF_TEST_CASE_WITHOUT_HEAD(load_file__file_not_found_error);
ATF_TEST_CASE_BODY(load_file__file_not_found_error)
{
    xlua::state state;
    ATF_REQUIRE_THROW_RE(xlua::file_not_found_error, "missing.lua",
                         state.load_file("missing.lua"));
}


ATF_TEST_CASE_WITHOUT_HEAD(load_string__ok);
ATF_TEST_CASE_BODY(load_string__ok)
{
    xlua::state state;
    state.load_string("return 2 + 3");
    ATF_REQUIRE(lua_pcall(raw(state), 0, 1, 0) == 0);
    ATF_REQUIRE_EQ(5, lua_tointeger(raw(state), -1));
    lua_pop(raw(state), 1);
}


ATF_TEST_CASE_WITHOUT_HEAD(load_string__fail);
ATF_TEST_CASE_BODY(load_string__fail)
{
    xlua::state state;
    REQUIRE_API_ERROR("luaL_loadstring", state.load_string("-"));
}


ATF_TEST_CASE_WITHOUT_HEAD(new_table);
ATF_TEST_CASE_BODY(new_table)
{
    xlua::state state;
    state.new_table();
    ATF_REQUIRE_EQ(1, lua_gettop(raw(state)));
    ATF_REQUIRE(lua_istable(raw(state), -1));
    lua_pop(raw(state), 1);
}


ATF_TEST_CASE_WITHOUT_HEAD(new_userdata);
ATF_TEST_CASE_BODY(new_userdata)
{
    xlua::state state;
    int* pointer = state.new_userdata< int >();
    *pointer = 1234;
    ATF_REQUIRE_EQ(1, lua_gettop(raw(state)));
    ATF_REQUIRE(lua_isuserdata(raw(state), -1));
    lua_pop(raw(state), 1);
}


ATF_TEST_CASE_WITHOUT_HEAD(next__empty);
ATF_TEST_CASE_BODY(next__empty)
{
    xlua::state state;
    luaL_dostring(raw(state), "t = {}");

    lua_getglobal(raw(state), "t");
    lua_pushstring(raw(state), "this is a dummy value");
    lua_pushnil(raw(state));
    ATF_REQUIRE(!state.next(-3));
    lua_pop(raw(state), 2);
}


ATF_TEST_CASE_WITHOUT_HEAD(next__many);
ATF_TEST_CASE_BODY(next__many)
{
    xlua::state state;
    luaL_dostring(raw(state), "t = {}; t[1] = 100; t[2] = 200");

    lua_getglobal(raw(state), "t");
    lua_pushnil(raw(state));

    ATF_REQUIRE(state.next(-2));
    ATF_REQUIRE_EQ(3, lua_gettop(raw(state)));
................................................................................
    lua_pop(raw(state), 1);
}


ATF_TEST_CASE_WITHOUT_HEAD(open_base);
ATF_TEST_CASE_BODY(open_base)
{
    xlua::state state;
    check_modules(state, "");
    state.open_base();
    check_modules(state, "base");
}


ATF_TEST_CASE_WITHOUT_HEAD(open_all);
ATF_TEST_CASE_BODY(open_all)
{
    xlua::state state;
    check_modules(state, "");
    state.open_all();
    // Best-effort attempt at looking for a bunch of possible modules.
    ATF_REQUIRE(is_available(state, "assert"));
    ATF_REQUIRE(is_available(state, "debug.getinfo"));
    ATF_REQUIRE(is_available(state, "package.path"));
    ATF_REQUIRE(is_available(state, "string.byte"));
................................................................................
    ATF_REQUIRE(is_available(state, "table.concat"));
}


ATF_TEST_CASE_WITHOUT_HEAD(open_string);
ATF_TEST_CASE_BODY(open_string)
{
    xlua::state state;
    check_modules(state, "");
    state.open_string();
    check_modules(state, "string");
}


ATF_TEST_CASE_WITHOUT_HEAD(open_table);
ATF_TEST_CASE_BODY(open_table)
{
    xlua::state state;
    check_modules(state, "");
    state.open_table();
    check_modules(state, "table");
}


ATF_TEST_CASE_WITHOUT_HEAD(pcall__ok);
ATF_TEST_CASE_BODY(pcall__ok)
{
    xlua::state state;
    luaL_loadstring(raw(state), "function mul(a, b) return a * b; end");
    state.pcall(0, 0, 0);
    state.get_global_table();
    lua_pushstring(raw(state), "mul");
    lua_gettable(raw(state), -2);
    lua_pushinteger(raw(state), 3);
    lua_pushinteger(raw(state), 5);
................................................................................
    lua_pop(raw(state), 2);
}


ATF_TEST_CASE_WITHOUT_HEAD(pcall__fail);
ATF_TEST_CASE_BODY(pcall__fail)
{
    xlua::state state;
    lua_pushnil(raw(state));
    REQUIRE_API_ERROR("lua_pcall", state.pcall(0, 0, 0));
}


ATF_TEST_CASE_WITHOUT_HEAD(pop__one);
ATF_TEST_CASE_BODY(pop__one)
{
    xlua::state state;
    lua_pushinteger(raw(state), 10);
    lua_pushinteger(raw(state), 20);
    lua_pushinteger(raw(state), 30);
    state.pop(1);
    ATF_REQUIRE_EQ(2, lua_gettop(raw(state)));
    ATF_REQUIRE_EQ(20, lua_tointeger(raw(state), -1));
    lua_pop(raw(state), 2);
}


ATF_TEST_CASE_WITHOUT_HEAD(pop__many);
ATF_TEST_CASE_BODY(pop__many)
{
    xlua::state state;
    lua_pushinteger(raw(state), 10);
    lua_pushinteger(raw(state), 20);
    lua_pushinteger(raw(state), 30);
    state.pop(2);
    ATF_REQUIRE_EQ(1, lua_gettop(raw(state)));
    ATF_REQUIRE_EQ(10, lua_tointeger(raw(state), -1));
    lua_pop(raw(state), 1);
}


ATF_TEST_CASE_WITHOUT_HEAD(push_boolean);
ATF_TEST_CASE_BODY(push_boolean)
{
    xlua::state state;
    state.push_boolean(true);
    ATF_REQUIRE_EQ(1, lua_gettop(raw(state)));
    ATF_REQUIRE(lua_toboolean(raw(state), -1));
    state.push_boolean(false);
    ATF_REQUIRE_EQ(2, lua_gettop(raw(state)));
    ATF_REQUIRE(!lua_toboolean(raw(state), -1));
    ATF_REQUIRE(lua_toboolean(raw(state), -2));
................................................................................
    lua_pop(raw(state), 2);
}


ATF_TEST_CASE_WITHOUT_HEAD(push_cxx_closure);
ATF_TEST_CASE_BODY(push_cxx_closure)
{
    xlua::state state;
    state.push_integer(15);
    state.push_cxx_closure(cxx_multiply_closure, 1);
    lua_setglobal(raw(state), "cxx_multiply_closure");

    ATF_REQUIRE(luaL_dostring(raw(state),
                              "return cxx_multiply_closure(10)") == 0);
    ATF_REQUIRE_EQ(150, lua_tointeger(raw(state), -1));
................................................................................
    lua_pop(raw(state), 1);
}


ATF_TEST_CASE_WITHOUT_HEAD(push_cxx_function__ok);
ATF_TEST_CASE_BODY(push_cxx_function__ok)
{
    xlua::state state;
    state.push_cxx_function(cxx_divide);
    lua_setglobal(raw(state), "cxx_divide");

    ATF_REQUIRE(luaL_dostring(raw(state), "return cxx_divide(17, 3)") == 0);
    ATF_REQUIRE_EQ(5, lua_tointeger(raw(state), -2));
    ATF_REQUIRE_EQ(2, lua_tointeger(raw(state), -1));
    lua_pop(raw(state), 2);
}


ATF_TEST_CASE_WITHOUT_HEAD(push_cxx_function__fail_exception);
ATF_TEST_CASE_BODY(push_cxx_function__fail_exception)
{
    xlua::state state;
    state.push_cxx_function(cxx_divide);
    lua_setglobal(raw(state), "cxx_divide");

    ATF_REQUIRE(luaL_dostring(raw(state), "return cxx_divide(15, 0)") != 0);
    ATF_REQUIRE_MATCH("Divisor is 0", lua_tostring(raw(state), -1));
    lua_pop(raw(state), 1);
}


ATF_TEST_CASE_WITHOUT_HEAD(push_cxx_function__fail_anything);
ATF_TEST_CASE_BODY(push_cxx_function__fail_anything)
{
    xlua::state state;
    state.push_cxx_function(cxx_divide);
    lua_setglobal(raw(state), "cxx_divide");

    ATF_REQUIRE(luaL_dostring(raw(state), "return cxx_divide(-3, -1)") != 0);
    ATF_REQUIRE_MATCH("Unhandled exception", lua_tostring(raw(state), -1));
    lua_pop(raw(state), 1);
}


ATF_TEST_CASE_WITHOUT_HEAD(push_cxx_function__fail_overflow);
ATF_TEST_CASE_BODY(push_cxx_function__fail_overflow)
{
    xlua::state state;
    state.push_cxx_function(raise_long_error);
    lua_setglobal(raw(state), "fail");

    ATF_REQUIRE(luaL_dostring(raw(state), "return fail(900)") != 0);
    ATF_REQUIRE_MATCH(std::string(900, 'A'), lua_tostring(raw(state), -1));
    lua_pop(raw(state), 1);

................................................................................
    lua_pop(raw(state), 1);
}


ATF_TEST_CASE_WITHOUT_HEAD(push_integer);
ATF_TEST_CASE_BODY(push_integer)
{
    xlua::state state;
    state.push_integer(12);
    ATF_REQUIRE_EQ(1, lua_gettop(raw(state)));
    ATF_REQUIRE_EQ(12, lua_tointeger(raw(state), -1));
    state.push_integer(34);
    ATF_REQUIRE_EQ(2, lua_gettop(raw(state)));
    ATF_REQUIRE_EQ(34, lua_tointeger(raw(state), -1));
    ATF_REQUIRE_EQ(12, lua_tointeger(raw(state), -2));
................................................................................
    lua_pop(raw(state), 2);
}


ATF_TEST_CASE_WITHOUT_HEAD(push_nil);
ATF_TEST_CASE_BODY(push_nil)
{
    xlua::state state;
    state.push_nil();
    ATF_REQUIRE_EQ(1, lua_gettop(raw(state)));
    ATF_REQUIRE(lua_isnil(raw(state), -1));
    state.push_integer(34);
    ATF_REQUIRE_EQ(2, lua_gettop(raw(state)));
    ATF_REQUIRE(!lua_isnil(raw(state), -1));
    ATF_REQUIRE(lua_isnil(raw(state), -2));
................................................................................
    lua_pop(raw(state), 2);
}


ATF_TEST_CASE_WITHOUT_HEAD(push_string);
ATF_TEST_CASE_BODY(push_string)
{
    xlua::state state;

    {
        std::string str = "first";
        state.push_string(str);
        ATF_REQUIRE_EQ(1, lua_gettop(raw(state)));
        ATF_REQUIRE_EQ(std::string("first"), lua_tostring(raw(state), -1));
        str = "second";
................................................................................
    lua_pop(raw(state), 2);
}


ATF_TEST_CASE_WITHOUT_HEAD(push_value);
ATF_TEST_CASE_BODY(push_value)
{
    xlua::state state;

    lua_pushinteger(raw(state), 10);
    lua_pushinteger(raw(state), 20);
    state.push_value(-2);
    ATF_REQUIRE_EQ(3, lua_gettop(raw(state)));
    ATF_REQUIRE_EQ(10, lua_tointeger(raw(state), -1));
    ATF_REQUIRE_EQ(20, lua_tointeger(raw(state), -2));
................................................................................
    lua_pop(raw(state), 3);
}


ATF_TEST_CASE_WITHOUT_HEAD(raw_get);
ATF_TEST_CASE_BODY(raw_get)
{
    xlua::state state;

    luaL_openlibs(raw(state));
    ATF_REQUIRE(luaL_dostring(
        raw(state), "t = {foo=123} ; setmetatable(t, {__index=1})") == 0);
    lua_getglobal(raw(state), "t");
    lua_pushinteger(raw(state), 9876);
    lua_pushstring(raw(state), "foo");
................................................................................
    lua_pop(raw(state), 3);
}


ATF_TEST_CASE_WITHOUT_HEAD(raw_set);
ATF_TEST_CASE_BODY(raw_set)
{
    xlua::state state;

    luaL_openlibs(raw(state));
    ATF_REQUIRE(luaL_dostring(
        raw(state), "t = {} ; setmetatable(t, {__newindex=1})") == 0);
    lua_getglobal(raw(state), "t");
    lua_pushinteger(raw(state), 876);
    lua_pushstring(raw(state), "foo");
................................................................................
    lua_pop(raw(state), 3);
}


ATF_TEST_CASE_WITHOUT_HEAD(registry_index);
ATF_TEST_CASE_BODY(registry_index)
{
    xlua::state state;
    lua_pushvalue(raw(state), xlua::registry_index);
    lua_pushstring(raw(state), "custom_variable");
    lua_pushstring(raw(state), "custom value");
    lua_settable(raw(state), -3);
    lua_pop(raw(state), 1);
    ATF_REQUIRE(luaL_dostring(raw(state),
                              "return custom_variable == nil") == 0);
    ATF_REQUIRE(lua_isboolean(raw(state), -1));
................................................................................
    lua_pop(raw(state), 1);
}


ATF_TEST_CASE_WITHOUT_HEAD(set_global);
ATF_TEST_CASE_BODY(set_global)
{
    xlua::state state;
    lua_pushinteger(raw(state), 3);
    state.set_global("test_variable");
    ATF_REQUIRE(luaL_dostring(raw(state), "return test_variable + 1") == 0);
    ATF_REQUIRE(lua_isnumber(raw(state), -1));
    ATF_REQUIRE_EQ(4, lua_tointeger(raw(state), -1));
    lua_pop(raw(state), 1);
}


ATF_TEST_CASE_WITHOUT_HEAD(set_metatable);
ATF_TEST_CASE_BODY(set_metatable)
{
    xlua::state state;
    ATF_REQUIRE(luaL_dostring(
        raw(state),
        "mt = {}\n"
        "mt.__add = function(a, b) return a[1] + b end\n"
        "numbers = {}\n"
        "numbers[1] = 5\n") == 0);

................................................................................
    lua_pop(raw(state), 1);
}


ATF_TEST_CASE_WITHOUT_HEAD(set_table__ok);
ATF_TEST_CASE_BODY(set_table__ok)
{
    xlua::state state;
    ATF_REQUIRE(luaL_dostring(raw(state), "t = { a = 1, bar = 234 }") == 0);
    lua_getglobal(raw(state), "t");

    lua_pushstring(raw(state), "bar");
    lua_pushstring(raw(state), "baz");
    state.set_table(-3);
    ATF_REQUIRE_EQ(1, lua_gettop(raw(state)));
................................................................................
    lua_pop(raw(state), 1);
}


ATF_TEST_CASE_WITHOUT_HEAD(set_table__nil);
ATF_TEST_CASE_BODY(set_table__nil)
{
    xlua::state state;
    lua_pushnil(raw(state));
    lua_pushinteger(raw(state), 1);
    lua_pushinteger(raw(state), 2);
    REQUIRE_API_ERROR("lua_settable", state.set_table(-3));
    lua_pop(raw(state), 3);
}


ATF_TEST_CASE_WITHOUT_HEAD(to_boolean);
ATF_TEST_CASE_BODY(to_boolean)
{
    xlua::state state;
    lua_pushboolean(raw(state), 0);
    lua_pushboolean(raw(state), 1);
    ATF_REQUIRE(!state.to_boolean(-2));
    ATF_REQUIRE(state.to_boolean(-1));
    lua_pop(raw(state), 2);
}


ATF_TEST_CASE_WITHOUT_HEAD(to_integer);
ATF_TEST_CASE_BODY(to_integer)
{
    xlua::state state;
    lua_pushinteger(raw(state), 12);
    lua_pushstring(raw(state), "foobar");
    ATF_REQUIRE_EQ(12, state.to_integer(-2));
    lua_pop(raw(state), 2);
}


ATF_TEST_CASE_WITHOUT_HEAD(to_string);
ATF_TEST_CASE_BODY(to_string)
{
    xlua::state state;
    lua_pushstring(raw(state), "foobar");
    lua_pushinteger(raw(state), 12);
    ATF_REQUIRE_EQ("foobar", state.to_string(-2));
    ATF_REQUIRE_EQ("12", state.to_string(-1));
    lua_pop(raw(state), 2);
}


ATF_TEST_CASE_WITHOUT_HEAD(to_userdata);
ATF_TEST_CASE_BODY(to_userdata)
{
    xlua::state state;
    {
        int* pointer = static_cast< int* >(
            lua_newuserdata(raw(state), sizeof(int)));
        *pointer = 987;
    }

    lua_pushinteger(raw(state), 3);
................................................................................
    lua_pop(raw(state), 2);
}


ATF_TEST_CASE_WITHOUT_HEAD(upvalue_index);
ATF_TEST_CASE_BODY(upvalue_index)
{
    xlua::state state;
    lua_pushinteger(raw(state), 25);
    lua_pushinteger(raw(state), 30);
    lua_pushcclosure(raw(state), c_get_upvalues, 2);
    lua_setglobal(raw(state), "c_get_upvalues");

    ATF_REQUIRE(luaL_dostring(raw(state),
                              "return c_get_upvalues()") == 0);