Issue with string.sub() and string.len()

Hey, so I have this script, which is suppose to loop through every letter of the message below, and change the amount of letters the message contains to the amount of times the loop has ran. I can’t really explain in great detail, because I’m literal trash at explaining, but the issue is, uhm… well, take a look?

   local message = "hello there"
   
   for i = 1,message:len() do
       message = string.sub(message,1,i)
       print(message)
       wait(.125)
   end

Output:

    h
    h
    h --it just keeps prints out the first letter of the message

I was expecting a little something like this:

    h
    he
    hel
    hell
    hello --and so forth

Sorry if I made some obvious mistake, or if I didn’t include enough information about the issue.

You’re assigning the variable message to h
So bascially this:

       message = string.sub(message,1,i)
       print(message)

is doing this:

message = string.sub("hello there", 1, 1)
message = string.sub("h", 1, 2)
message = string.sub("h", 1, 3)

I’d use “#str” instead of “str:len()”

1 Like

You’re overwriting the original message – when it comes to the first character, you’re overwriting the variable message with h, and it will keep returning h

The solution is not update the variable:

for i = 1, message:len() do
    local message = string.sub(message, 1, i)
    print(message)
    wait(0.125)
end

If you define a local variable outside in a scope, like for loops and functions, it’ll only be visible for that scope. When you define a variable with in a scope, this is called an “upvalue”

3 Likes

Oh yeahhhhh, I didn’t notice that, sorry. Thanks, both of you for responding!