Why do I have to create the same variable inside of a OnServerEvent Function?

Hello! I am a beginner scripter and learning about remote events through a Youtube video. Right now I’m confused about why I have to make “local leaderstats” and “local coins” again.
( As you can see, I had to make 2 “local leaderstats” and “local coins” inside of the whole script)

Can someone explain why this is necessary?

because variables that are inside functions cannot be global

something = 10

function yes()
   nothing = 5 -- will error, fix by doing local
end

you can’t make that variable global, because it’s… closed in a function
if those variables were previously defined not inside a function, then you can freely do variable = value

to answer your question
variables cannot be carried over to other functions unless you return them

you have to define leaderstats and coins again in the .OnServerEvent function because .PlayerAdded doesn’t return anything, it only adds content to the player, and in order to access it in a later function, you have to define it

1 Like

You have to do this because the playeradded event fires for each player, creating leaderstats. However, when you want to change one, it doesn’t know which player to target, so you need to redefine which player’s leaderstats to change. (I hope I explained that well lol.)

wow thank you for your detailed explanation! I totally understand it now. TYSM

Thank you, sir! I understand it now

not error, just warn
image

1 Like

damn okay i didn’t know that

1 Like