Weird question about a talbe/for loop

I have this code that puts a weapons name and price from a table on a button.
It works fine, but it doesn’t make the buttons in the order that it reads the tables/in the order they are created.


	local addWeapon = {}

	addWeapon["CZ75"] = {
		name = "CZ-75",
		model = "INSERT WORLD MODEL HERE",
		class = "cw_ber_cz75",
		price = 10,
		amount = 1,
		allowed = { TEAM_CITIZEN },
		category = "Pistols"
	}

	addWeapon["P228"] = {
		name = "Sig P228",
		model = "INSERT WORLD MODEL HERE",
		class = "cw_ber_p228",
		price = 20,
		amount = 1,
		allowed = { TEAM_CITIZEN },
		category = "Pistols"
	}

	--display info
	for k, v in pairs( addWeapon ) do

		local ListItem = List:Add( "DButton" ) //Add DPanel to the DIconLayout
		ListItem:SetSize( Frame:GetWide() - 28, 40 ) //Set the size of it
		ListItem:SetText( addWeapon[k].name .. " ($" .. addWeapon[k].price .. ")" )
		ListItem.DoClick = function()

			chat.AddText( "Player clicked" .. ListItem:GetText() )

		end

	end

It displays the P228 first, then the CZ75, even though the tables are created the other way around, and their keys are 1 and 2.
Is there something I’m missing?
I could use SortedPairs, but that just puts them all in numerical order, how would I sort them in the order they are created?

Their keys aren’t 1 and 2, they’re CZ75 and P228…

It doesn’t matter what order your table’s keys are in when you create it

Can I just ask what are you creating/coding ? Cause you been creating a lot of threas and I am curious now XD

Correct me if I’m wrong ( And I may be ) but the do loop cycles through randomly unless specifically stated you want “THIS” argument to be first…

Try changing your keys to actually be numbers, then use ipairs to go through them rather than pairs

What you could do, is make a table whose keys are 1, 2, 3, etc. And the value is the name of the weapon. Then iterate through that table and use addweapon[v]

For example,



local addWeapon = {}

addWeapon[1] = {
	name = "CZ-75",
	model = "INSERT WORLD MODEL HERE",
	class = "cw_ber_cz75",
	price = 10,
	amount = 1,
	allowed = { TEAM_CITIZEN },
	category = "Pistols"
}

addWeapon[2] = {
	name = "Sig P228",
	model = "INSERT WORLD MODEL HERE",
	class = "cw_ber_p228",
	price = 20,
	amount = 1,
	allowed = { TEAM_CITIZEN },
	category = "Pistols"
}

--display info
for k, v in ipairs( addWeapon ) do

	local ListItem = List:Add( "DButton" ) //Add DPanel to the DIconLayout
	ListItem:SetSize( Frame:GetWide() - 28, 40 ) //Set the size of it
	ListItem:SetText( v.name .. " ($" .. v.price .. ")" )
	ListItem.DoClick = function()

		chat.AddText( "Player clicked" .. ListItem:GetText() )

	end

end


Need to add the closing bracket for one.

Fixed it, jesus christ everyone’s posting on this thread too fast for me to keep up

Thanks everyone for the help! I managed to get it to work.

Also, what I’m making is a secret! :ninja: