Why use string.len instead of #?

Why would using string.len be more useful than just writing a hashtag before a string? Don’t both count the string length regardless?

I think it’s just another example of meaningless abstraction. There’s pretty much no point to it, yeah

1 Like

string.len will return the exact amount of characters a string has, putting a hashtag before a variable which is a string would not count the characters. Putting a hashtag before a value is usually used in tables to have a certain variety of stuff in a table. If you put #string, unless apart of a table, this does nothing.

Actually, it does, putting # will return the length of the string, this is because hash invokes __len metamethod in the given object, that is if there is one.

3 Likes

Huh, I’ve been proven wrong, thank you for that I never knew that

As for your question, yes, they do the exact samething, however I suppose since # invokes the __len metamethod, you can use it on custom objects created by you (or someone else) with a metamethod named __len. As far as ik this won’t work the same with string.len() which is designed specifically for strings.

I use #string rather than string.len(string) because it’s faster to type. But you’re correct; they do the exact same thing

1 Like

I’ll clarify it here, the reason string functions are recommended over str:method is due to the lack of a performance implementation in Luau. The same logic applies to using the # operator.

Multiple benchmarks have shown that using the functions instead of metamethod behaviour has up to a 4x performance gain over str:method, its also worth noting that Luau implements fastcalling on the string library which makes it even faster over using metamethods.

1 Like