Search code examples
stringrandommirc

Script to generate random string not working


I'm trying to generate random string with white spaces but it is not working :

/rs {
  %i=1
  %r=$rand(1,50)
  %s=$rand(a,z)
  while(%i <= %r) {
    %i=%i+1
    %s=%s $+ $rand(a,z)
    if(1 == rand(1,4) %s=%s $+ $chr(32)
  }
  echo %s
}

Returns :

WHILE(%I Unknown command

Any ideas ?


Solution

  • You had some issues, those are just few of them.

    • Spaces: mSL statements are sensebile when it concerns to spaces, those you should put spaces between the while (expression), if (expression) and even %i = 1 and %r = $rand(1,50) etc'

    • Parenthesis: You probably have forgotten the little parenthesis at the space generator condition. Should be if (1 == rand(1,4)) %s=%s $+ $chr(32)

    • $ sign: You also forgotten to put this sign before this identifier rand(1,4) should be $rand(1,4)

    Fixed Snippet:

    rs {
      %i = 1
      %r = $rand(1,50)
      %s = $rand(a,z)
      while (%i <= %r) {
        %i = %i + 1
        %s = %s $+ $rand(a,z)
        if (1 == $rand(1,4)) %s = %s $chr(32)
    
      }
      echo -ag %s
    }
    

    I took the liberty of designing the code a bit different, now you can use it as $identifier instead of an alias, which will give you further flexibility and usability.

    Usages:

    • echo -ag $rs (default will be 50 characters long)
    • echo -ag $rs(20) (random string with length of 20 charcathers)
    • set %myName $rs(15) (will save the output random string into a constant variable)

    Snippet:

    rs {
      if (!$1) {
        tokenize 32 50
      }
    
      var %randString
      var %randStringLength = $rand(1, $1)
      var %i = 1
      while (%i <= %randStringLength) {
        %randString = %randString $+ $rand(a, z)
        if ($rand(1, 4) == 1) {
          %randString = %randString $chr(32)
        }
        inc %i
      }
      return %randString
    }