Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

This table insert prints nil?

This code prints nil, print is on line 10

local PeopleA = {}

script.Parent.MouseButton1Click:Connect(function()
	table.insert(PeopleA, (Random.new(tick()):NextInteger(1,6)), "Name1")
	table.insert(PeopleA, (Random.new(tick()):NextInteger(1,6)), "Name2")
	table.insert(PeopleA, (Random.new(tick()):NextInteger(1,6)), "Name3")
	table.insert(PeopleA, (Random.new(tick()):NextInteger(1,6)), "Name4")
	table.insert(PeopleA, (Random.new(tick()):NextInteger(1,6)), "Name5")
	table.insert(PeopleA, (Random.new(tick()):NextInteger(1,6)), "Name6")
	print(PeopleA[1])
	for i, v in pairs(PeopleA) do
		for a, b in pairs(script.Parent.Parent:GetChildren()) do
			local sp = Random.new(tick()):NextInteger(1,#PeopleA)
			if b.Name == "Person" and b.Text == "" then
		        b.Text = PeopleA[sp]
				table.remove(PeopleA, sp)
			wait()
			end
		end
		
		end
end)

Thanks!

1 answer

✓ Accepted answer

There are a few reasons this doesn't work:

  • Random.new(tick()) reseeds the random number generator; this should only be done once, otherwise you get the same Integer each time.
  • Even if the numbers were random, you shouldn't tell table.insert to insert a value into the 3rd index if your table doesn't have at least 2 elements! table.insert treats your table like a list/array - and these are not supposed to have nil elements between non-nil elements. If the first thing you do is insert 5 into the 2nd index, your table is {nil, 5}, which is invalid.

If you want a shuffle algorithm:

local function shuffle(list, rnd)
	local index
	local n = #list
	for i = 1, n - 1 do
		index = rnd and rnd:NextNumber(i, n) or math.random(i, n)
		list[i], list[index] = list[index], list[i]
	end
end

local PeopleA = {"Name1", "Name2", "Name3", "Name4", "Name5", "Name6"}
local rnd = Random.new()
script.Parent.MouseButton1Click:Connect(function()
	shuffle(PeopleA, rnd)
	print(unpack(PeopleA))
	local peopleIndex = 1
	for i, v in ipairs(PeopleA) do
		for a, b in ipairs(script.Parent.Parent:GetChildren()) do
			if b.Name == "Person" and b.Text == "" then
				b.Text = PeopleA[peopleIndex]
				peopleIndex = peopleIndex + 1
			end
		end
	end
end)

Modification notes:

  • We initialize rnd to Random.new, which uses tick() by default
  • We don't use sp because we've already shuffled the names, so we can just use the 1st name in the list, then the 2nd, etc
  • I removed the wait() because it's unnecessary (but you could add it back in if desired)

This discussion is preserved as it was. New answers, comments, and votes are closed.