Hello ScriptingHelpers community! Back again with a question.
How would i pick a random string from a table with strings? I've got a line here, edit as you'd like.
Strings = { "line1" "line2" "line3" } for i, v in pairs(Strings) do print(math.random(1, v)) -- "1" takes 1 string from the table and "v" prints the string selected end
Please fix my script if it is not correct, thanks!
A mistake that I have caught is that you did not put a comma(,) or a semicolon(;) after each string. That is very important to have so you could access those strings. Another thing you must know is that if you put # before a table name, that gets the number of keys (in this case strings) in your table. The final thing you should know that if you want to get the strings in your table or access anything in the table, you would have to do Strings[Which string you want to get]
. You have 3 strings, so you are able to put in between the brackets 1, 2 or 3. Here is your fixed script.
local Strings = {"line1", "line2","line3"} local selectedIndex = math.random(1,#Strings) local selectedString = Strings[selectedIndex] print('Selected String is ' .. selectedString) print('Selected Index is ' .. selectedIndex)
If you wanted to make things truly random, you would put math.randomseed(tick()) on the top of your script.
math.randomseed(tick()) local Strings = {"line1", "line2","line3"} local selectedIndex = math.random(1,#Strings) local selectedString = Strings[selectedIndex] print('Selected String is ' .. selectedString) print('Selected Index is ' .. selectedIndex)
Please accept my answer if it fixed your script. If not, please ask questions in the comments.
You dont need to user a for i,v in pairs loop for this.
strings = {"line1","line2","line3"} --our strings print(strings[math.random(3)]) --indexes the table with a random number from 1 to 3, and prints it
iddash did a great job explaining the MAIN part. math.random will often not call completely random numbers. The first number will allways be the same. You should use randomseeds to randomize the PATTERN of which they are generated.