Dzsozi (h03)

Get the correct table index depending on other values

Recommended Posts

Hello!

While I was improving a resource, I came across a small problem;

I would like to get the correct value based on vehicle health. I have a table similar like this:

["somekey"] = {
  [75] = "somevar1", -- view it as health limits, so when the health is lower or between the current and the next, more lower number, then I can add a property to my vehicle
  [50] = "somevar2",
  [25] = "somevar3",
},

What I want to do is if the health of the vehicle goes under 75 then return "somevar1", when it goes under 50 then return "somevar2" and when it goes under 25 then return "somevar3" and so on. Basically I would like to check if the vehicle's health is between the given indexes/limits and return the correct table value for it. I am guessing that I will need a custom range function but I don't know how to get started and how to select between the indexes depending on a given number when calling the function. I hope I was understandable and someone can help me out, I really need to get this work, please help!

Edited by Dzsozi (h03)

Share this post


Link to post
4 hours ago, Dzsozi (h03) said:

Basically I would like to check if the vehicle's health is between the given indexes/limits and return the correct table value for it

That table structure will not work well.

 

Back to basic:

local list = {
	{value = 25, id = "a"},
	{value = 50, id = "b"},
	{value = 75, id = "c"},
	{value = 100}
}


function findSomething(value)
	for i = 1, #list - 1 do
		if value >= list[i].value and value < list[i + 1].value then
			return list[i]
		end
	end
end

local result = findSomething(27)
if result then
	print(result.id)
end

 

Edited by IIYAMA
  • Thanks 1

Share this post


Link to post

Thank you!

I had to change some things up a little bit to match my needs and get it done correctly, it's working now just as I wanted to!

  • Like 1

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.