Weird roblox `--!strict` warning when using tonumber(value), that doesn't happen on tostring(value)

I’m not sure if to categorise it as bug reports or script support since this may be intended and not a bug.

Take a look at this image.


Note that I’m manually converting it since I’m using --!strict
What the hell does that mean? You’re telling me you cannot convert something to a number when using --!strict?
Also, it’s even weirder when you use tostring(value), because NO WARNING.
image
Which means that for some reason tonumber(value) and tostring(value) don’t work for the same types. Should they support all types when using --!strict?
If it’s a bug then point it out in the comments. Otherwise just tell me what am I doing wrong.

1 Like

tonumber() returns number?
index is already a number, setting index to a potentially nil value causes the type error.

What you want instead is:

index = assert(tonumber(index), "Index must be convertible to a number!")

It works, but why?
The warning is located in the tonumber, not in the assert. Also, as I mentioned how is the tostring not warning? I’m confused.
Is it both me doing it wrong and a bug?

tostring always returns a string, tonumber doesn’t always return a number.

The warning is because you’re setting index to number? when it should be a number. You can test this with:

local temp = tonumber(index)
index = temp

The assert makes sure index is never assigned to a nil value, whereas in your example you would set it to nil first and then assert it.

1 Like

This is still confusing me. I didn’t set it to number?, I set it to number. When I’m changing it to tostring and changing the type to a string then it does not show that same warning. Why is that?

A simple way around this is to just use type casting, tonumber(index) :: number

1 Like

index is a number and it should never have nil assigned to it. The function tonumber can return nil however, so with what you’ve written it’s possible that tonumber returns nil and gets assigned to index. That’s why you’re getting a warning about it.

tostring never returns nil so it’s not an issue.

If you’re 100% certain tonumber will return a number and not nil (which it should), then do what @D4_rrk suggested.

1 Like

Thanks for the explanation! Not sure who to give solution cause like you explained why it worked and others gave the answer.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.