Example #1
0
/// 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 nresults The number of results to expect; -1 for any.
///
/// \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 nresults)
{
    assert(nresults >= -1);
    const int height = s.get_top();

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

    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);
}