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

Random name generator crashes after several attempts?

Hi, I am making a Random name generator which will generate names according to the selected theme(modern, ancient etc)

This is my module script...

local module = {}

local Ancient = {...}
local Modern = {...}
local Normal = {...}
local Steampunk = {...}

function module:GenerateName(age)
	if age == "Ancient" then
		print("anceint sf")
		local firstName = Ancient[math.random(1, #Ancient)]
		local lastName = Ancient[math.random(1, #Ancient)]	
		while firstName == lastName do
			local lastName = Ancient[math.random(1, #Ancient)]	
			wait()
		end
		return firstName.." "..lastName
	elseif age == "Normal" or nil then
		local firstName = Normal[math.random(1, #Normal)]
		local lastName = Normal[math.random(1, #Normal)]	
		while firstName == lastName do
			local lastName = Normal[math.random(1, #Normal)]	
			wait()
		end
		return firstName.." "..lastName
	elseif age=="Steampunk" then
		local firstName = Steampunk[math.random(1, #Steampunk)]
		local lastName = Steampunk[math.random(1, #Steampunk)]	
		while firstName == lastName do
			local lastName = Steampunk[math.random(1, #Steampunk)]	
			wait()
		end
		return firstName.." "..lastName
	end
end

return module

And I called it here, using a local script

local Button = script.Parent
local Background = Button.Parent
local TextBox = Background:WaitForChild("TextBox")
local Module = require(script:WaitForChild("RandomName") )

local Debounce = false

Button.MouseButton1Click:connect(function()
	if Debounce == false then
		Debounce = true
		if _G.NameAge == "Ancient" then
			local name = Module:GenerateName(_G.NameAge)
			TextBox.Text = name
		elseif _G.NameAge == "Normal" or nil then
			local name = Module:GenerateName(_G.NameAge)
			TextBox.Text = name
		elseif _G.NameAge == "Steampunk" then
			local name = Module:GenerateName(_G.NameAge)
			TextBox.Text = name
		end	
		Debounce = false	
	end
end)

Thanks :3

1 answer

local firstName = Ancient[math.random(1, #Ancient)]
local lastName = Ancient[math.random(1, #Ancient)]  
while firstName == lastName do
       local lastName = Ancient[math.random(1, #Ancient)]  
       wait()
end

Every time this cycles, it creates a new local variable (meaning only the code within that loop will "see" it), rather than changing the current one. This means that the first "local lastName" will never change, and the cycle will never stop.

To fix this, change it to:

local firstName = Ancient[math.random(1, #Ancient)]
local lastName = Ancient[math.random(1, #Ancient)]  
while firstName == lastName do
       lastName = Ancient[math.random(1, #Ancient)]  --Removed "local"
       wait()
end

If this is the problem, I'd repeat this for the other if statements

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