How to randomly select an item from this table

Hello o/
I have this module script for items in my game however I’m currently making a test shop and I’m trying to figure out how I can randomly select something from it

local items = {
	
	Sword = {
		weaponType = "Sword",
		Rarity = "Rare",
		rarityTextColor = Rare,
		equipmentSlot = "Mainhand",
		Tier = 7,
		Power = 7,
		Stamina = 3,
		Agility = 5,
	},
	Shield = {
		Rarity = "Epic",
		rarityTextColor = Epic,
		equipmentSlot = "Offhand",
		Tier = 1,
		Power = 3,
		Stamina = 7,
		Agility = 4,
	},
	["Rusty Helmet"] = {
		Rarity = "Common",
		rarityTextColor = Common,
		equipmentSlot = "Head",
		Tier = 5,
		Power = 10,
		Stamina = 10,
		Agility = 10,
	},
	
}

Also another question I have is how can I maybe make this cleaner or efficient? (if possible) My current code basically relies on making sure the naming for this is correct or kind of just breaks when I add an item to the players inventory I do it as a string so “Sword” and then I save it to a variable called item or something so when I go to check I just check if items[item] exists but if I put “Swordd” or the thing in the module script is incorrect it just doesn’t work. I mean idk if there’s anything I can do about this I guess I’d just have to make sure everything is spelt correctly, but if there’s a way to like idk just to make it easier I guess

2 Likes

The solution to your randomness problem is this.

local itemsList = {}
for key, value in pairs(items) do
    table.insert(itemsList, key)
end

-- to get a random item
local randomItem = items[itemsList[math.random(#itemsList)]]

There isn’t really an autocorrect solution outside of the Intellisense features of Studio, and it would be fairly complicated to make a good one yourself.

1 Like