Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
2

What is tostring? Why do we use it and why is it useful?

Asked by 3 years ago
Edited 3 years ago

Hello there, I've searched the whole YouTube, Roblox Forums etc. I have found a explanation on the Developer Hub but I can't understand what it means. What I want to ask is what is tostring? Why do we use it and why is it helpful?

2 answers

Log in to vote
2
Answered by 3 years ago

tostring() is a function that converts (almost) any given data type to a string. There are numerous uses for it:

  • Converting something to a string to perform formatting on it.
  • Converting a number, or almost any other data type, to a string for concatenation purposes. In Roblox only, you are able to concatenate a number to a string without using tostring(). However, you need tostring() for any other data type.
  • Converting a boolean to a string for printing purposes, or GUI purposes.
  • etc.

For conditional purposes, tostring() will viably compare its given data type to a string. Two examples of this:

print(tostring(10) == "10") -- true
print(tostring(5 * 6 > 4^2) == tostring(true)) -- true

When converting tables to strings, it will just give the identifier instead of the table contents:

print(tostring({})) -- table: <identifier>

For concatenating numbers, tostring() is not necessary. This print, for example...

print(5 .. 6) -- 56

...will convert both numbers to strings before concatenating them.

Ad
Log in to vote
1
Answered by 3 years ago

tostring is a function that converts a given number to a string. This can be useful for stuff like if statements. If you want to compare say, a math equation to a TextBox's text, you will need to use tostring (or tonumber) to compare the two, as two different data types can not be compared.

1
it does not have to be number, it converts any given value to string: Instances, tables, etc. imKirda 4491 — 3y

Answer this question