How do i get the next value in a table?

I’m trying to make an iterator that goes through a table when you press E.
I’ve searched here and came to the conclusion that next helps, however that does not accurately get the next value
Here’s a short summary of the code:

local things = {
[50] = "something"
[200] = "something"
[600] = "something" }

local selected = 50

I want to get the next closest value after 50, wich is 200. How do i do that?

tables with non-ordinal keys have undefined order, you should not rely on the order of iteration of the non-ordinal keys of any table.

You could iterate everything in the table and find the closest key than the value of the selected variable by keeping track on what’s the closest value iterated so far. However, I don’t think this is efficient.

Alternatively, you could create a table consisting of ascending values, in your summary it would consist of 50, 200, 600 in that order and keep track of the index. (and to get the closest value, you’d do index+1 or index-1, depending on which item in that index is closer)

Edit: mis-read the question. Sorry.

1 Like

I found that this came with lots of errors if the selected value is not in the table so you’ll need some sort of check but otherwise this should work

local things = {
[50] = "something",
[200] = "something",
[600] = "something"
}
local selected = 50
local nextValue
local success, err = pcall(function()
    nextValue = next(things,selected)
end)
local things = {
    [50] = "something",
    [200] = "something",
    [600] = "something"
}
local selected = 50

function getNext()
    if not things[selected] then return end
    return next(things, selected)
end

print(getNext()) -- 200

This answer and the answer before this relies on the order of the tables in Lua to be deterministic.
Unfortunately, that is not the case. The key could return 600 and technically it is working normally as the order of the tables in Lua(u) is an undefined behaviour.

next errors if the key provided does not exist or is nil. Not sure what are the benefits of catching exceptions on invalid next key over checking if the key of the table is nil.

2 Likes

True, I assumed the table was predetermined by the OP but in the case that it is not, the code would not work. Also I personally prefer using catches over checking if nil :person_shrugging: .

local currentdistance = 0
local currentindex = 0

local target = 50 

for index, name in things do
  if index > target then
    if index-target > currentdistance then
      currentdistance, currentindex= index-target, index
    end
  end
end

currentindex will be your answer.

This is exactly the problem I ran into.
Is there a better way of composing the table though? This table is generated by getting the layoutorders of some buttons in an UIListLayout.