Make get_current_track_index safer to use

This prevents problems like issue #1861.
This commit is contained in:
Alexander van Gessel 2017-10-30 21:17:04 +01:00
parent e0efa082d7
commit 749646a75b
3 changed files with 10 additions and 6 deletions

View file

@ -96,11 +96,11 @@ static int impl_music_get(lua_State* L) {
}
if(strcmp(m, "current_i") == 0) {
size_t i = sound::get_current_track_index();
if(i >= sound::get_num_tracks()) {
lua_pushnil(L);
auto current_index = sound::get_current_track_index();
if(current_index) {
lua_pushinteger(L, current_index.value() + 1);
} else {
lua_pushinteger(L, i + 1);
lua_pushnil(L);
}
return 1;
}

View file

@ -191,8 +191,11 @@ std::vector<std::shared_ptr<sound::music_track>>::const_iterator find_track(cons
namespace sound
{
unsigned int get_current_track_index()
boost::optional<unsigned int> get_current_track_index()
{
if(current_track_index >= current_track_list.size()){
return {};
}
return current_track_index;
}
std::shared_ptr<music_track> get_current_track()

View file

@ -17,6 +17,7 @@
#include "events.hpp"
#include "sound_music_track.hpp"
#include <boost/optional.hpp>
#include <string>
class config;
@ -104,7 +105,7 @@ void set_sound_volume(int vol);
void set_bell_volume(int vol);
void set_UI_volume(int vol);
unsigned int get_current_track_index(); // This function may return a value >= get_num_tracks(). Use with caution
boost::optional<unsigned int> get_current_track_index();
std::shared_ptr<sound::music_track> get_current_track();
std::shared_ptr<sound::music_track> get_previous_music_track();
void set_previous_track(std::shared_ptr<music_track>);