Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Finding the lowest value help?

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

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

2 comments

0

Beat me to it.

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

This discussion is preserved as it was. New answers, comments, and votes are closed.