How do I do this?

so I have a script that allows the player to press escape and the mouse will unlock and become visible, how would I go about making it so that when I press escape again, the mouse will lock and become hidden again?

Update() {
if getkey(esc) {
mouseflag = !mouseflag;
DoSomething(mouseflag)
}
}

private void DoSomething(bool flag) {
if(flag)
 // do unlock visi
else
 // do lock invisi
}

Your question is in mostly answered in the example from the docs:
Screen.lockCursor.
Few small changes, you can get rid of this:

 void OnMouseDown() {
    Screen.lockCursor = true;
 }

And modify this:

 if (Input.GetKeyDown("escape"))
    Screen.lockCursor = !Screen.lockCursor;

Also the mouse should have been clicked inside the webplayer window once and remain inside, for it to work