Path: blob/main/contrib/lutok/examples/bindings.cpp
102968 views
// Copyright 2012 Google Inc.1// All rights reserved.2//3// Redistribution and use in source and binary forms, with or without4// modification, are permitted provided that the following conditions are5// met:6//7// * Redistributions of source code must retain the above copyright8// notice, this list of conditions and the following disclaimer.9// * Redistributions in binary form must reproduce the above copyright10// notice, this list of conditions and the following disclaimer in the11// documentation and/or other materials provided with the distribution.12// * Neither the name of Google Inc. nor the names of its contributors13// may be used to endorse or promote products derived from this software14// without specific prior written permission.15//16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.2728/// \file examples/bindings.cpp29/// Showcases how to define Lua functions from C++ code.30///31/// A major selling point of Lua is that it is very easy too hook native C and32/// C++ functions into the runtime environment so that Lua can call them. The33/// purpose of this example program is to show how this is done by using Lutok.3435#include <cassert>36#include <cstdlib>37#include <iostream>38#include <map>39#include <sstream>40#include <stdexcept>41#include <string>4243#include <lutok/exceptions.hpp>44#include <lutok/operations.hpp>45#include <lutok/state.ipp>464748/// Calculates the factorial of a given number.49///50/// \param i The postivie number to calculate the factorial of.51///52/// \return The factorial of i.53static int54factorial(const int i)55{56assert(i >= 0);5758if (i == 0)59return 1;60else61return i * factorial(i - 1);62}636465/// A custom factorial function for Lua.66///67/// \pre stack(-1) contains the number to calculate the factorial of.68/// \post stack(-1) contains the result of the operation.69///70/// \param state The Lua state from which to get the function arguments and into71/// which to push the results.72///73/// \return The number of results pushed onto the stack, i.e. 1.74///75/// \throw std::runtime_error If the input parameters are invalid. Note that76/// Lutok will convert this exception to lutok::error.77static int78lua_factorial(lutok::state& state)79{80if (!state.is_number(-1))81throw std::runtime_error("Argument to factorial must be an integer");82const int i = state.to_integer(-1);83if (i < 0)84throw std::runtime_error("Argument to factorial must be positive");85state.push_integer(factorial(i));86return 1;87}888990/// Program's entry point.91///92/// \param argc Length of argv. Must be 2.93/// \param argv Command-line arguments to the program. The first argument to94/// the tool has to be a number.95///96/// \return A system exit code.97int98main(int argc, char** argv)99{100if (argc != 2) {101std::cerr << "Usage: bindings <number>\n";102return EXIT_FAILURE;103}104105// Create a new Lua session and load the print() function.106lutok::state state;107state.open_base();108109// Construct a 'module' that contains an entry point to our native factorial110// function. A module is just a Lua table that contains a mapping of names111// to functions. Instead of creating a module by using our create_module()112// helper function, we could have used push_cxx_function on the state to113// define the function ourselves.114std::map< std::string, lutok::cxx_function > module;115module["factorial"] = lua_factorial;116lutok::create_module(state, "native", module);117118// Use a little Lua script to call our native factorial function providing119// it the first argument passed to the program. Note that this will error120// out in a controlled manner if the passed argument is not an integer. The121// important thing to notice is that the exception comes from our own C++122// binding and that it has been converted to a lutok::error.123std::ostringstream script;124script << "print(native.factorial(" << argv[1] << "))";125try {126lutok::do_string(state, script.str(), 0, 0, 0);127return EXIT_SUCCESS;128} catch (const lutok::error& e) {129std::cerr << "ERROR: " << e.what() << '\n';130return EXIT_FAILURE;131}132}133134135