Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

How to change variable type after deceleration for all lines after the change #3236

Answered by tomlau10
EmekC asked this question in Q&A
Discussion options

---@param dmginfo CTakeDamageInfo
function foo(dmginfo)
 ---@type Player | Entity
 local attacker = dmginfo:GetAttacker()
 
 # attacker must be player after this!
 if not attacker:IsPlayer() then return end
 # but I still get errors like: Cannot assign `Entity|Player` to parameter `Player`.
 # How can i cast it as such and not Player|Entity
end

I want to cast a variable type after declaration for the global scope, my idea is that after i check if the attacker is a certain type i want to cast it as just this type for all the code below

You must be logged in to vote

I believe that you ran into another strange known issue: #2326
where the @cast is not working if you file doesn't have a trailing newline 🙈

Could you try to add a new empty newline at the end of your file?

Replies: 2 comments 3 replies

Comment options

use @cast https://luals.github.io/wiki/annotations/#cast
=> ---@cast attacker Player

You must be logged in to vote
3 replies
Comment options

I've already tried.
image

function ENT:OnTakeDamage(dmginfo)
 ---@type Player|Entity
 local attacker = dmginfo:GetAttacker()
 if not attacker:IsPlayer() then return end
 ---@cast attacker Player
 local wep = attacker:GetActiveWeapon()
Comment options

I believe that you ran into another strange known issue: #2326
where the @cast is not working if you file doesn't have a trailing newline 🙈

Could you try to add a new empty newline at the end of your file?

Answer selected by EmekC
Comment options

good catch!, works wonders now, would have never guessed it myself

Comment options

image

If it’s Vscode-EmmyLua, You can use return_cast here to enable automatic inference.

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet

AltStyle によって変換されたページ (->オリジナル) /