Scripting Help | Choosing a random character from a string?

Hey! So I’m making a script where it generates glitchy text in real time, that I can use in my game, however I don’t see why its not working. Script:

local ListOfGlitch = "¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽž"

local function generateGlitch(amt)
	local c = ""
	for i = 1,amt do
		local t = math.random(1,#ListOfGlitch)
		c = string.format("%s%s",c,t)
	end
	print(tostring(c))
end

generateGlitch(5)

You are setting the variable c to a new string every iteration, and im not sure if you understand string.format here.

local ListOfGlitch = "¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽž"

local function generateGlitch(amt)
    local result = { }

    for _ = 1, amt do
        local i = math.random(#ListOfGlitch)
        table.insert(result, ListOfGlitch:sub(i, i))
    end
    print(table.concat(result))
end

I also inserted the characters into a table instead and concatenated the results altogether into 1 string via table.concat. Concatenating would create a new string each iteration which can be slow.

1 Like

I had a feeling i needed to organize it into tables like that. However, one thing i never understood is the use of table.concat. Anyways, tysm for the help!

table.concat(t, delimiter, i, j) concatenates all the strings and numbers in a table to 1 string. delimiter is what to separate each element with. Defaults to an empty string "", i is where to start concatenating. By default this is 1. j is where to stop concatenating. Defaults to #t.

That makes alot more sense. Thank you!

1 Like