Community discussions

MikroTik App
 
DoubleDB
newbie
Topic Author
Posts: 25
Joined: Thu Feb 20, 2020 12:53 am

Unable to set a local variable

Tue Jul 05, 2022 7:51 pm

: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.
 
User avatar
rextended
Forum Guru
Forum Guru
Posts: 11968
Joined: Tue Feb 25, 2014 12:49 pm
Location: Italy
Contact:

Re: Unable to set a local variable  [SOLVED]

Tue Jul 05, 2022 8:01 pm

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:

7 code

{

: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"

}

Who is online

Users browsing this forum: No registered users and 26 guests