-
-
Notifications
You must be signed in to change notification settings - Fork 331
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[Feature request] Implicit casts for common conversions #3027
Comments
IMO an explicit cast should be needed for this kind of use case. local b = ""
---@cast b +number
print(b) --> string|number
b = tonumber(b) or 0 --[[>
This variable is defined as type `string`. Cannot convert its type to `number`.
- Type `integer` cannot match `string`
- Type `number` cannot match `string`Lua Diagnostics.(cast-local-type)
]]
If that is fixed, then we can at least have something like local b = ""
---@cast b -string,+number
b = tonumber(b) or 0 |
Agreed, implicitly casting is probably not exactly sound. Not sure how other dynamic languages with types as an "afterthought" handle this situation. However, note that the implicit cast wouldn't be new behavior, it already does that automatically! So my original request is poorly phrased, it's really about the type inference (and I guess the bug you are pointing out). For example:
If the type was inferred as number|string here based on the later assignment everything would just work magically :) |
I suggest redefining a variable with the same name to resolve the conflict, which is very common in Rust. local var = "123131"
local var = tonumber(var) |
But then this will violate another rule: redefined-local |
I got some code for parsing command line flags/user inputs that commonly uses patterns like this
The fix is to define b as
string|number
in the declaration, but it's a bit cumbersome, especially if I just wantb
as a number:So it would be nice if common type conversion patterns like this could be recognized automatically and either allow the cast or infer the type as string|number from the beginning.
Edit: See comment below, the implicit cast is already happening, this is really about type inference based on later assignments. Which may or may not be a good idea.
The text was updated successfully, but these errors were encountered: