How do you get a random table from a table?

I am trying to make somewhat of a combat system all in code but i came across a problem. I made enemy stats and weapons all in tables
Example:

local Weapons = {
Hands = {["Name"] = "Hands";["Damage"] = {5,10}};
Pipe = {["Name"] = "Pipe";["Damage"] = {10,15}};
Bat = {["Name"] = "Bat";["Damage"] = {15,20}}
}
local Targets = {
	Guy = {["Name"] = "Guy";["Health"] = 25;["Weapon"] = Weapons["Hands"]};
	GuywithPipe = {["Name"] = "Guy with Pipe";["Health"] = 25;["Weapon"] = Weapons["Pipe"]} 
}

but I tried to make it so it will pick a random table from the ‘Targets’ table and it came up with errors and empty interval stuff.

while wait(2) do
	local Target = Targets[math.random(1,#Targets)]
	if Target ~= nil then
		Attack(Target)
	else
		break
	end
end

so i am very confused on how im supposed to get a random table from a table.

The reason it’s giving you an error, is in your Targets table, you’re using strings as indexes. But then trying to index with a number.

An easy fix would be to just remove the "Guy = " and "GuywithPipe = " and let Roblox set numerical indexes.

Can you make an example of how that would look?

It’s simply changing your code from this

local Weapons = {
Hands = {["Name"] = "Hands";["Damage"] = {5,10}};
Pipe = {["Name"] = "Pipe";["Damage"] = {10,15}};
Bat = {["Name"] = "Bat";["Damage"] = {15,20}}
}
local Targets = {
	Guy = {["Name"] = "Guy";["Health"] = 25;["Weapon"] = Weapons["Hands"]};
	GuywithPipe = {["Name"] = "Guy with Pipe";["Health"] = 25;["Weapon"] = Weapons["Pipe"]} 
}

to this

local Weapons = {
Hands = {["Name"] = "Hands";["Damage"] = {5,10}};
Pipe = {["Name"] = "Pipe";["Damage"] = {10,15}};
Bat = {["Name"] = "Bat";["Damage"] = {15,20}}
}
local Targets = {
	{["Name"] = "Guy";["Health"] = 25;["Weapon"] = Weapons["Hands"]};
	{["Name"] = "Guy with Pipe";["Health"] = 25;["Weapon"] = Weapons["Pipe"]} 
}
1 Like