Loop through table in order

Yeah it seems to be working if I’m correct I’m gonna add the rest of the code and test the final version.

@jumbopushpop112 @ZethusImam So the buy all thing works but their is an issue .

local ToolLibrary = {}

for index, object in pairs(Tools) do
	object.Index = index
	ToolLibrary[object.Name] = object
end

local DefaultTool = ToolLibrary.Test1 -- This is an example of the equipped tool the player has
local NextTool = Tools[DefaultTool.Index + 1] -- example of the locked tool the player has

How would I get the equipped tool and the next tool from the buy all

for _, v in ipairs(shopData.Energies) do -- maintain order when iterating through a table numerically indexed
    		local name, price = v.ItemName, v.Price
			print(name, price)
			if price <= player.leaderstats.Coins.Value then
				client.Data.Coins = client.Data.Coins - price
			else
				print(name,price)
				break
			end
		end

So this works but it goes into the negatives if I have an item which is the same amount as the player’s coins which the price is 100 and the player’s coin is 100.

Try something like this:

for i = 1, #Table do
    local Curr = Table[i];
    local Name, Price = Curr.Name, Curr.Price;
    if Price <= Coins then
        -- Give
        Coins -= Price;
    else
        break;
    end
end

Obviously replace Coins and Player with the actual coins and player values.

3 Likes

Key order is unspecified. ipairs() returns index-value pairs and is mostly used for numeric tables.
Non numeric keys in an array are ignored, while the index order is deterministic (in numeric order).

I was able to fix the negative thing and everything works out fine.

But you’d need to check if the Price is equal to the amount of coins because if it is then the player’s coins value would go into the negatives.

Well I ended up changing a lot of stuff and this seems like a better way to handle it instead of using a generic method so thanks. I also ended up changing stuff though but it all worked out.

Anytime, happy to help! Glad we solved your problem.

1 Like

Thanks for helping me out I appreciate it!

My pleasure, glad I could help.

1 Like

Also is a numeric loop able to iterate a table?

Not really sure, Java is my main language. But I looked up Lua numeric loops and I guess you could try.