I know that Articulating has a good answer and that using string.gmatch is a more efficient way of looping through each individual character, but there's one slight problem with it!
Namely, that you can't use a timeBetween of less than 1/30 - which I found was quite annoying when writing a similar function myself, I wanted a way for much longer strings to still animate, but not take so long, which they would, even with the minimum delay. Think about it, a 60 character sentence would take 2 whole seconds, or even worse, this paragraph would take precisely 13 seconds!
One way of compensating for this is to add more than 1 character from the input string to the output Text field per iteration. This method also uses coroutines so that you can easily schedule multiple simultaneous text animations, it also calculates how many characters to add per iteration, so this allows you to use delay times of much less than 1/30.
function TypeLabel(label, text, characterDelay)
coroutine.resume(coroutine.create(function()
local step = characterDelay and math.ceil(1/(60*characterDelay)) or 1
local len = text:len()
for i = 1, step * (math.floor(len/step) + 1)+1, step do
d = i > len and len or i
label.Text = text:sub(1,d)
wait(characterDelay)
end
end))
end
4 comments
Thanks. 1+ for that one.
Interesting solution! I normally use a for loop with string.len but this is more elegant. I'm wondering if this is also a better method in terms of efficiency!
String.gmatch is MUCH faster than looping with string.len. I discovered this while using a function to return all characters in a string, using your for loop solution. I then utilised string.gmatch instead, and the speed increase was amazing when using large strings.
I profiled this and didn't see any more than a 10% speed up from using match over a traditional loop (although using string.len instead of the # operator was slower, but that's because of the table access in that expression, not the operation of finding length). I find the straightforward infringementing loop solution would be more understandable in most cases, so do you have a good example of cod