Search code examples
checkboxluavt100

Lua: Search key in table, increment index if not and retry


Situation:

table = { this, that, something else, x_coord, y_coord }
table.x_coord = { 1,2,3,4,7,8,n}
table.y_coord = { 2,4,5,9,n} -- numbers aren't fix
table.check_boxes = { [12] = a function,
                      [14] = a function,
                      [15] = a function,
                      [24] = a function,
                      [29] = a function,
                         ....(n) }

As you can see, the x/y_coords forming check_boxes. For example:

table.x_coord[1]..table.y_coord[1] ~ table.check_boxes[1]

I use this to move the cursor in the Terminal between the check_boxes.

The problem now is in my cursormovement. Currently I got a function that's searching for the next x/y_coord to the left/right/up/down depending on the given input (arrow-keys). With return/space I call the function behind the checkbox.

Now, that could set the Cursor on positions where no check_boxes are given. Actually that's not a big deal, because when input == space/return, an inputhandler calls the function at

table.check_boxes[table.x_coorx[x_index]..table.y_coords[y_index]]

So if the cursor doesn't point on a function, just nothing happens. But now I want the cursor to be forced to the next check_box. What can I do?

My Idea so far:

following function either for x or y, depending on input left/right up/down:

while true do
    for k, v in pairs(table.check_boxes) do
        if(table.x_coord[x_index] .. table.y_coord[y_index] == k then break end
    end -- break -> okay, coord is at a checkbox

    x_index = x_index + 1 -- or -1 

    if table.x_coord[x_index] == nil then 
        x_index = 1
    end
end

The Problem now is that the last if will not allow cases like x_coord = {1,3} because it will set x_index to 1 if 2 is reached.

Any tips?

Edit: Now I got that one going:

function cursorTioNextBoxRight()
    searc_index = x_index
    search = true
    while search do
        search_index = search_index + 1

        if search_index > #table.x_coord then
            search_index = 1
        end

    for k, v in pairs(table.check_boxes) do
        if tonumber(table.x_coord[search_index..table.y_coord[y_index] == k then
            x_index = search_index -- YAAAY
            search = false
            break
         end
     end
end

I'ts damn slow.


Solution

  • function cursorTioNextBoxRight()
    searc_index = x_index
    search = true
    while search do
        search_index = search_index + 1
    
        if search_index > #table.x_coord then
            search_index = 1
        end
    
    for k, v in pairs(table.check_boxes) do
        if tonumber(table.x_coord[search_index..table.y_coord[y_index] == k then
            x_index = search_index -- YAAAY
            search = false
            break
         end
     end
    

    end