Revert to lowest number

I have this dialogue

[0] = {
	[1] = {Msg = "Hello there!", Type = 'Normal'},
	[2] = {Msg = "Are you ready to begin your adventure?", Type = 'Question', 
		Responses = {
			[1] = {
				Answer = "I am",
				Direct = 3
			},
		}
	},
	[3] = {Msg = "Excellent! First thing you need to go do is collect wood.", Type = 'Normal'},
	[4] = {Msg = "To collect wood simply go punch some trees.", Type = 'Normal'},
	[5] = {Msg = "Go collect 5 wood and return back here for your next objective!", Type = 'End', UpdateStory = true}
},
[1] = {
	[1] = {Msg = "Go collect 5 wood and return back here for your next objective!", Type = 'End', UpdateStory = false},
},
[2] = {
	[1] = {Msg = "Thank you for collecting the wood! I am happy now", Type = 'Normal'},
	[2] = {Msg = "You can go do some other stuff now", Type = 'End', UpdateStory = true},
},
[8] = {
	[1] = {Msg = "I have another quest for you!", Type = 'Normal'},
	[2] = {Msg = "Come back with a sword!", Type = 'End', UpdateStory = true},
},

Probably hard to read and explain, but basically each dialogue table is wrapped in a number, shown here are [0], [1], [2] and [8] These are basically story progress ID’s. So when players story is at 1, it’ll play the dialogue located in [1]. Problem rises when their story is 3, or anything between 2-8.

As I get their story like so

TotalMessages = DialogueData[NPC].Messages[StoryValue][NextSpeech]

So if my StoryValue is 2, it’d get the Dialogue in [2]. But if my StoryValue is 3 4, 5, etc… it errors out, as there are no story lines for those numbers.

So my question is, how can I get it to revert to the lowest number? So if there StoryValue is 7, it’d go to [2], and if their StoryValue is 9 it’d go to [8]?

if DialogueData[NPC].Messages[StoryValue][NextSpeech] then
	TotalMessages = DialogueData[NPC].Messages[StoryValue][NextSpeech]
else
	-- Player is further into story or in between stories (3-7, 9-inf. example) give the previous dialogue
end

Perhaps just “count downwards” from your StoryValue value, until you find a ‘is not nil’ element, or zero is reached?

local function findStoryValue(npc, startingStoryValue)
  for i = startingStoryValue, 0, -1 do
    if DialogueData[npc].Messages[i] ~= nil then
      return i
    end
  end
  return 0
end

local tempStoryValue = findStoryValue(NPC, StoryValue)
DialogueData[NPC].Messages[tempStoryValue]
1 Like