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