xref: /netbsd-src/external/bsd/lutok/dist/examples/bindings.cpp (revision a15637525a498a84b68d8b44b1c7ec01de4b564a)
1*a1563752Sjmmv // Copyright 2012 Google Inc.
2*a1563752Sjmmv // All rights reserved.
3*a1563752Sjmmv //
4*a1563752Sjmmv // Redistribution and use in source and binary forms, with or without
5*a1563752Sjmmv // modification, are permitted provided that the following conditions are
6*a1563752Sjmmv // met:
7*a1563752Sjmmv //
8*a1563752Sjmmv // * Redistributions of source code must retain the above copyright
9*a1563752Sjmmv //   notice, this list of conditions and the following disclaimer.
10*a1563752Sjmmv // * Redistributions in binary form must reproduce the above copyright
11*a1563752Sjmmv //   notice, this list of conditions and the following disclaimer in the
12*a1563752Sjmmv //   documentation and/or other materials provided with the distribution.
13*a1563752Sjmmv // * Neither the name of Google Inc. nor the names of its contributors
14*a1563752Sjmmv //   may be used to endorse or promote products derived from this software
15*a1563752Sjmmv //   without specific prior written permission.
16*a1563752Sjmmv //
17*a1563752Sjmmv // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18*a1563752Sjmmv // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19*a1563752Sjmmv // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20*a1563752Sjmmv // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21*a1563752Sjmmv // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22*a1563752Sjmmv // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23*a1563752Sjmmv // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24*a1563752Sjmmv // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25*a1563752Sjmmv // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26*a1563752Sjmmv // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27*a1563752Sjmmv // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28*a1563752Sjmmv 
29*a1563752Sjmmv /// \file examples/bindings.cpp
30*a1563752Sjmmv /// Showcases how to define Lua functions from C++ code.
31*a1563752Sjmmv ///
32*a1563752Sjmmv /// A major selling point of Lua is that it is very easy too hook native C and
33*a1563752Sjmmv /// C++ functions into the runtime environment so that Lua can call them.  The
34*a1563752Sjmmv /// purpose of this example program is to show how this is done by using Lutok.
35*a1563752Sjmmv 
36*a1563752Sjmmv #include <cassert>
37*a1563752Sjmmv #include <cstdlib>
38*a1563752Sjmmv #include <iostream>
39*a1563752Sjmmv #include <map>
40*a1563752Sjmmv #include <sstream>
41*a1563752Sjmmv #include <stdexcept>
42*a1563752Sjmmv #include <string>
43*a1563752Sjmmv 
44*a1563752Sjmmv #include <lutok/exceptions.hpp>
45*a1563752Sjmmv #include <lutok/operations.hpp>
46*a1563752Sjmmv #include <lutok/state.ipp>
47*a1563752Sjmmv 
48*a1563752Sjmmv 
49*a1563752Sjmmv /// Calculates the factorial of a given number.
50*a1563752Sjmmv ///
51*a1563752Sjmmv /// \param i The postivie number to calculate the factorial of.
52*a1563752Sjmmv ///
53*a1563752Sjmmv /// \return The factorial of i.
54*a1563752Sjmmv static int
factorial(const int i)55*a1563752Sjmmv factorial(const int i)
56*a1563752Sjmmv {
57*a1563752Sjmmv     assert(i >= 0);
58*a1563752Sjmmv 
59*a1563752Sjmmv     if (i == 0)
60*a1563752Sjmmv         return 1;
61*a1563752Sjmmv     else
62*a1563752Sjmmv         return i * factorial(i - 1);
63*a1563752Sjmmv }
64*a1563752Sjmmv 
65*a1563752Sjmmv 
66*a1563752Sjmmv /// A custom factorial function for Lua.
67*a1563752Sjmmv ///
68*a1563752Sjmmv /// \pre stack(-1) contains the number to calculate the factorial of.
69*a1563752Sjmmv /// \post stack(-1) contains the result of the operation.
70*a1563752Sjmmv ///
71*a1563752Sjmmv /// \param state The Lua state from which to get the function arguments and into
72*a1563752Sjmmv ///     which to push the results.
73*a1563752Sjmmv ///
74*a1563752Sjmmv /// \return The number of results pushed onto the stack, i.e. 1.
75*a1563752Sjmmv ///
76*a1563752Sjmmv /// \throw std::runtime_error If the input parameters are invalid.  Note that
77*a1563752Sjmmv ///     Lutok will convert this exception to lutok::error.
78*a1563752Sjmmv static int
lua_factorial(lutok::state & state)79*a1563752Sjmmv lua_factorial(lutok::state& state)
80*a1563752Sjmmv {
81*a1563752Sjmmv     if (!state.is_number())
82*a1563752Sjmmv         throw std::runtime_error("Argument to factorial must be an integer");
83*a1563752Sjmmv     const int i = state.to_integer();
84*a1563752Sjmmv     if (i < 0)
85*a1563752Sjmmv         throw std::runtime_error("Argument to factorial must be positive");
86*a1563752Sjmmv     state.push_integer(factorial(i));
87*a1563752Sjmmv     return 1;
88*a1563752Sjmmv }
89*a1563752Sjmmv 
90*a1563752Sjmmv 
91*a1563752Sjmmv /// Program's entry point.
92*a1563752Sjmmv ///
93*a1563752Sjmmv /// \param argc Length of argv.  Must be 2.
94*a1563752Sjmmv /// \param argv Command-line arguments to the program.  The first argument to
95*a1563752Sjmmv ///     the tool has to be a number.
96*a1563752Sjmmv ///
97*a1563752Sjmmv /// \return A system exit code.
98*a1563752Sjmmv int
main(int argc,char ** argv)99*a1563752Sjmmv main(int argc, char** argv)
100*a1563752Sjmmv {
101*a1563752Sjmmv     if (argc != 2) {
102*a1563752Sjmmv         std::cerr << "Usage: bindings <number>\n";
103*a1563752Sjmmv         return EXIT_FAILURE;
104*a1563752Sjmmv     }
105*a1563752Sjmmv 
106*a1563752Sjmmv     // Create a new Lua session and load the print() function.
107*a1563752Sjmmv     lutok::state state;
108*a1563752Sjmmv     state.open_base();
109*a1563752Sjmmv 
110*a1563752Sjmmv     // Construct a 'module' that contains an entry point to our native factorial
111*a1563752Sjmmv     // function.  A module is just a Lua table that contains a mapping of names
112*a1563752Sjmmv     // to functions.  Instead of creating a module by using our create_module()
113*a1563752Sjmmv     // helper function, we could have used push_cxx_function on the state to
114*a1563752Sjmmv     // define the function ourselves.
115*a1563752Sjmmv     std::map< std::string, lutok::cxx_function > module;
116*a1563752Sjmmv     module["factorial"] = lua_factorial;
117*a1563752Sjmmv     lutok::create_module(state, "native", module);
118*a1563752Sjmmv 
119*a1563752Sjmmv     // Use a little Lua script to call our native factorial function providing
120*a1563752Sjmmv     // it the first argument passed to the program.  Note that this will error
121*a1563752Sjmmv     // out in a controlled manner if the passed argument is not an integer.  The
122*a1563752Sjmmv     // important thing to notice is that the exception comes from our own C++
123*a1563752Sjmmv     // binding and that it has been converted to a lutok::error.
124*a1563752Sjmmv     std::ostringstream script;
125*a1563752Sjmmv     script << "print(native.factorial(" << argv[1] << "))";
126*a1563752Sjmmv     try {
127*a1563752Sjmmv         lutok::do_string(state, script.str());
128*a1563752Sjmmv         return EXIT_SUCCESS;
129*a1563752Sjmmv     } catch (const lutok::error& e) {
130*a1563752Sjmmv         std::cerr << "ERROR: " << e.what() << '\n';
131*a1563752Sjmmv         return EXIT_FAILURE;
132*a1563752Sjmmv     }
133*a1563752Sjmmv }
134