What is the difference between string.sub() and string:sub()

string.sub("Hi",1,2)
and
string:sub(1,2)

They work exactly the same, so what’s the difference? Does one run faster than the other or performs better in general?

There is no difference if I’m correct.

string.sub("String", Min, Max)
("String"):sub(Min, Max)
1 Like

There’s no difference in terms of what function gets called. Strings have their metatable set to something along the lines of {__index = string}, so every method you can access on the global string table, you can access on strings.

However, using the global string table is faster as Luau can detect that those functions never change, and therefore use imports to slightly speed up your function execution. When you use :sub on a variable, Luau has no idea if it’s a string or not, so it can’t optimize those at compile time.

2 Likes