When sudoing/suing/etc, how do the various user-ID indicators get set?

real UID effective UID TTY owner1 2 $SUDO_USER
su new new old
sudo new3 new old old
setuid old new old

("new" is the user that the script runs as, "old" is what the user originally logged in as)

1 as determined by running who am i or logname

2 This data is unavailable if there's no TTY (for instance, when running under 'cron' or under a web server)

3 unless stay_setuid is specified in /etc/sudoers