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

math.random returning number?

The math.random for a string is returning a number instead a string? After I say the correct work then it error's again with this...

attempt to index upvalue "Word" ( a number value )

local Word=''

local ChatTable={
'Apple',	
'Clock',
'Mouse',
'Trash',
'Bird',
'Ipod',
}

function NewWord(plr)
for _,v in pairs(ChatTable) do
	local z = math.random(1,#v)   
 -- This returns a number value BUT I need it to return a string value
		Word = z  
	end
wait()
	print(Word) -- prints "5"
		Note(plr,'The New Word Is ['..Word..']',(45/2/9)) 
end

1 answer

✓ Accepted answer

math.random() will always return a number, it'll never return a string.

I'm assuming that what you're trying to do is have the script select a random string from the table "ChatTable"

If so, you'll have to use the math.random() as an index value to locate the item in the table, like so:

local Table = {
	"a";
	"b";
	"c";
	"d";
}

local RandomString = Table[ math.random(1, #Table) ] --This will get return the element from the table corresponding to the index. According to this, the index will be a random integer between 1 and the size of the table

Your script will have to be edited like so:

local Word=''

local ChatTable={
'Apple',    
'Clock',
'Mouse',
'Trash',
'Bird',
'Ipod',
}

function NewWord(plr)
Word = ChatTable[ math.random(1, #ChatTable) ]
wait()
Note(plr,'The New Word Is ['..Word..']',(45/2/9)) 
end

Hope this helped!

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