Community discussions

 
rpra
newbie
Topic Author
Posts: 36
Joined: Tue Jan 24, 2012 8:43 pm

Empty array initialization

Mon Mar 31, 2014 1:54 pm

I want to use a global assoc array in my script for storing some host->ip pairs, and I've encountered a problem:
when I first time define variable, it has type = "nothing", and can't be used as an array.

I have to check it's type and push some value to it, and then I can use a construct like
:global IP;
:if ([:typeof $IP] = "nothing") do={:set $IP {""};}

:set ($IP->$hostname) $ipaddress


It could be much easier to explicitely define type during init.
 
User avatar
rextended
Forum Guru
Forum Guru
Posts: 2946
Joined: Tue Feb 25, 2014 12:49 pm
Location: Capalbio, Tuscany, Italy

Re: Empty array initialization

Mon Mar 31, 2014 11:17 pm

Try first to use right syntax:

:global IP; --> :global IP value=;

:if ([:typeof $IP] = "nothing") do={:set $IP {""};} --> :if ([:typeof $IP] = "nothing") do={ :set $IP value={""} }

And now think about possibilities:

:global newEmptyArray value={""};

or

:global newEmptyArray value=[:toarray ""];
I'm Italian, not English. Sorry for my imperfect grammar.
 
A9691
just joined
Posts: 13
Joined: Sat May 14, 2016 10:58 am

Re: Empty array initialization

Tue Jul 26, 2016 1:06 pm

The second solution is the right one: [:toarray ""] is a zero length array.
{""} is an array with one element which is a zero length string.
 
User avatar
boen_robot
Forum Guru
Forum Guru
Posts: 2411
Joined: Thu Aug 31, 2006 4:43 pm
Location: europe://Bulgaria/Plovdiv

Re: Empty array initialization

Tue Jul 26, 2016 4:54 pm

Also, one can use
({})
to have an empty array literal.
PEAR2_Net_RouterOS(1.0.0b6) - My API client in PHP
(Rate my posts? If you want... no pressure...)
 
Frozer
newbie
Posts: 40
Joined: Wed Apr 10, 2013 4:14 pm
Contact:

Re: Empty array initialization

Tue Oct 25, 2016 12:07 pm

Also, one can use
({})
to have an empty array literal.
Thank you, man!
 
Chupakabra303
just joined
Posts: 12
Joined: Tue Jun 20, 2017 3:07 pm

Re: Empty array initialization

Wed Sep 26, 2018 4:28 pm

I found out incorrect work for syntax :local Array1 ({})
Works correctly :local Array1 [:toarray ""]
:global fArrayTest do={
# correct work :local Array1 [:toarray ""]
#  :local Array1 [:toarray ""]
# BUG, incorrect work :local Array1 ({})
  :local Array1 ({})
  :set ($Array1->([:len $Array1])) [:len $Array1]
  :put "len(Array1): $[:len $Array1]"
  :put "Array1:"
  :put $Array1
}

Test sequence for :local Array1 ({})
[admin@MikroTik] > $fArrayTest;
len(Array1): 1
Array1:
0
[admin@MikroTik] > $fArrayTest;
len(Array1): 2
Array1:
0;1
[admin@MikroTik] > $fArrayTest;
len(Array1): 3
Array1:
0;1;2

Test sequence for :local Array1 [:toarray ""]
[admin@MikroTik] > $fArrayTest;
len(Array1): 1
Array1:
0
[admin@MikroTik] > $fArrayTest;
len(Array1): 1
Array1:
0
[admin@MikroTik] > $fArrayTest;
len(Array1): 1
Array1:
0

Who is online

Users browsing this forum: Google [Bot] and 16 guests