Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Finding the lowest value help?

Asked by
NotSoNorm 777 Moderation Voter
8 years ago

So I'm trying to make an inventory that when you click on the button, It finds the lowest value that is true and prints that, This is what I have and it keeps printing slot3 when it should print slot2

Slots = {
    Slot1 = false;
    Slot2 = true;
    Slot3 = true;
    Slot4 = true;
    Slot5 = true;
    Slot6 = true;
    Slot7 = true;
    Slot8 = true
}
local Inventory = {}
function Inventory:FindNextSlot(item)
    for i,v in pairs(Slots) do 
        if v == true then 
            local lowest = i
            print(lowest)
            break
        end 
    end
end
return Inventory

1 answer

Log in to vote
2
Answered by
Unclear 1776 Moderation Voter
8 years ago

Dictionary portions of tables are unordered. You cannot guarantee that the order that you have defined keys will be the same order that an iterator function will produce.

There are two ways you can go about this. The first way is to reorder your data structure and make it an array instead. This will guarantee the order because it is not defined as a dictionary.

Slots = {
    false;
    true;
    true;
    true;
    true;
    true;
    true;
    true
}
local Inventory = {}
function Inventory:FindNextSlot(item)
    for i,v in pairs(Slots) do 
        if v == true then 
            local lowest = i
            print("Slot" .. lowest) -- append "Slot" before printing
            break
        end 
    end
end
return Inventory

If you wish to preserve your structure as a dictionary, you can use the fact that you have numbers in the keys to help you out.

Slots = {
    Slot1 = false;
    Slot2 = true;
    Slot3 = true;
    Slot4 = true;
    Slot5 = true;
    Slot6 = true;
    Slot7 = true;
    Slot8 = true
}
local Inventory = {}
function Inventory:FindNextSlot(item)
    for index = 1, 8 do -- iterate through the # of slots
        local key = "Slot" .. index 
        if Slots[key] == true then 
            print(key)
            break
        end 
    end
end
return Inventory
0
Beat me to it. CodingEvolution 490 — 8y
1
You could also use a `pairs` and compare the indexes with `<`, as long as the slots are all the same digit length, the string comparison will work BlueTaslem 18071 — 8y
Ad

Answer this question