Example #1
0
/// 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 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 file.
unsigned int
lutok::do_file(state& s, const std::string& file, const int nresults)
{
    assert(nresults >= -1);
    const int height = s.get_top();

    stack_cleaner cleaner(s);
    try {
        s.load_file(file);
        s.pcall(0, nresults == -1 ? LUA_MULTRET : nresults, 0);
    } catch (const lutok::api_error& e) {
        throw lutok::error("Failed to load Lua file '" + file + "': " +
                           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);
}