Able to find 1st, 2nd... element on any table on other script

Basically, I made a random entity spawn script but this should be random and I want find table elements with numbers how I can?

local Entity = require(game.ServerScriptService.Entity)
local Zone = require(game.ServerScriptService.Zones)
local AllZones = script.Parent

while wait() do
	local StartAr = AllZones.StartArea:GetChildren()
	if #StartAr == Zone.StartArea["Max Entities"] then
		print("Stable")
	else
		wait(math.random(0.5, 1))
		Entity.SpawnEntity(tostring(Entity[1]), CFrame.new(AllZones.StartArea.Position.X - AllZones.StartArea.Size.X/2 + math.random(0, AllZones.StartArea.Size.X ), 2, AllZones.StartArea.Position.Z - AllZones.StartArea.Size.Z/2 + math.random(0, AllZones.StartArea.Size.Z )), AllZones.StartArea)
	end
end

Do something like this.

for i, element in ipairs(table) do
  -- do something with the element
end

:thinking:

1 Like

hardly understandable and your code seems bad but, quick solution that probably does what you want?

local Entity = require(game.ServerScriptService.Entity)
local Zone = require(game.ServerScriptService.Zones)
local AllZones = script.Parent
local EntityTLength=#Entity

while true do
	local StartAr = AllZones.StartArea:GetChildren()
	if #StartAr == Zone.StartArea["Max Entities"] then
		print("Stable")
	else
		task.wait(math.random(0.5, 1))
		Entity.SpawnEntity(tostring(Entity[math.random(EntityTLength)]), CFrame.new(AllZones.StartArea.Position.X - AllZones.StartArea.Size.X/2 + math.random(0, AllZones.StartArea.Size.X ), 2, AllZones.StartArea.Position.Z - AllZones.StartArea.Size.Z/2 + math.random(0, AllZones.StartArea.Size.Z )), AllZones.StartArea)
	end
	task.wait()
end

also you can use this table[1] -- it gives first element in table

local Entity = require(game.ServerScriptService.Entity)

Entity = {
[1] = “Grass”,
[2] = “Tree”,
[3] = “Tree_2”,
[4] = “Stone”,
[5] = “Iron”,
}

return Entity

Any ideas?
(Sorry for my bad English)

I’m not sure why you would want to do this, but you can use pairs to iterate the key-value pairs of a table, and you can use math.random’s min, max syntax to select a random integer from a range of integers.
local min, max = 1, #Entity

for _, entity in pairs(Entity) do
print(math.random(min, max), entity)
end

1 Like

I will try ur solution can u wait 1 min

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.