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
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