Unable to set a local variable

:local elem 0;
:local firstsession "";

:foreach sessid in=[/user-manager/session/find where user=testuser] do={
	if ($elem < 1) do={
		:set $firstsession [/user-manager/session/get $sessid started];
		:put message=("First session: ".$firstsession); # Works - shows "jun/11/2022 16:33:32"
		:set $elem 1;
	}
}
:put message=("User testuser, Session start: ".$firstsession); # Doesn't work - returns empty value

Any ideas why “set” only works within the foreach loop but I’m unable to read it outside of it? It just returns an empty value.

You test it on terminal?

on terminal
:local x 1
and on the 2nd line, local x do not longer exist.

On terminal you must start everytime with { and end with }
and use correct syntax:
{

:local elem 0
:local firstsession “never”
:local usr “testuser”

/user-manager/session
:foreach sessid in=[find where user=$usr] do={
if ($elem = 0) do={
:set firstsession [get $sessid started]
:put “First session: $firstsession”
}
:set elem ($elem + 1)
}

:put “User $usr have $elem session(s) and the first is started: $firstsession”

}