[Question]
  [
Many people know what a [truth machine](https://esolangs.org/wiki/Truth-machine) in programming is. But is time we kick things up a notch. Introducing, the extended truth machine! An extended truth machine takes two things as input, a integer `n` and a nonempty string `s`. It outputs `s` `n` times with optional trailing whitespace. However, if `n` is equal to `0`, you must output `s` until the program is manually stopped i.e. it should never terminate.
Also, if `n` is a negative number, then the string needs to be reversed. For example with `s=hello` and `n=-1`, output would be `olleh`.
Standard methods of input, any kind of output as long as it can handle infinite. If you have an answer that does not handle infinite, feel free to post it if it is interesting or in a language that cannot handle infinite output.
# Test Cases
```
n, s, output
5, "hello world", "hello worldhello worldhello worldhello worldhello world"
0, "PPCG", "PPCGPPCGPPCGPPCG..."
-2, "truThY", "YhTurtYhTurt"
2000, "o", "oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo"
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins!
[Here](https://codegolf.meta.stackexchange.com/a/12065/66833) is the original Sandbox post. Edits have been made to it. Thanks go to @ComradeSparklePony for creating the idea of this challenge
  
[Answer]
## Haskell, ~~57~~ 54 bytes
```
f 0=cycle
f n|n<0=f(-n).reverse|n>0=concat.replicate n
```
Explanation:
```
f 0           -- If n=0 ..
 =cycle       -- infinitely repeat the input
f n|n<0       -- Otherwise, if n<0 ..
 =f(-n)       -- call f with the negative of n ..
 .reverse     -- and the reverse of the input
 |n>0         -- Finally, if n>0 ..
 concat       -- concatenate the result of ..
 .replicate n -- repeating the input n times
```
-3 bytes thanks to @nimi
[Answer]
# PHP>=7.1, 67 Bytes
```
for([,$x,$y]=$argv,$z=$x<=>0;!$z||$x;$x-=$z)echo$x<0?strrev($y):$y;
```
Version with `list(,$x,$y)` instead of `[,$x,$y]`
[Try it online!](https://tio.run/##HYuxCoAgGAb33iL5BgMD5@yvoaG1PRoiKoMgsQiT3t2k4aa7M9qEsjbaJBjtelPPciaYjHRd07JBheWwfN/Oiws4gSejPxTwBFdSJVUK/75wCi4n@Gye9BGNrM/L2vnmcSnwqBA@ "PHP – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~17~~ ~~16~~ 14 bytes
```
0‹iR}¹Ä×¹_i[²?
```
[Try it online!](https://tio.run/##ASwA0/8wNWFiMWX//zDigLlpUn3CucOEw5fCuV9pW8KyP///NQpoZWxsbyB3b3JsZA "05AB1E – Try It Online")
**Explanation:**
```
0‹iR}¹Ä×¹_i[²?
0‹             Is the input negative?
  iR}          If so, reverse the second input.
     ¹Ä        Get the absolute value of the first input.
       ×       Repeat the string that many times.
        ¹_     Boolean NOT the first input. (Is the first input 0?)
          i    If so...
           [   Do forever...
            ²? Print the second input without a newline.
```
Saved 2 bytes thanks to @EriktheOutgolfer
[Answer]
# [MATL](https://github.com/lmendo/MATL), 37 bytes
```
jXJiXI0=?`1wtwDw]}I0>?I:"t]x}PI|:"t]x
```
[Try it online!](https://tio.run/##y00syfn/PyvCKzPC08DWPsGwvKTcpTy21tPAzt7TSqkktqI2wLMGzPj/P043jssQAA "MATL – Try It Online")
Explanation:
```
j            % input string
XJ           % copy to clipboard J
i            % input
XI           % copy to clipboard I
0            % number literal
=            % is equal? (element-wise, singleton expansion)
?            % if
  `          % do...while
    1        % number literal
    w        % swap elements in stack
    t        % duplicate elements
    w        % swap elements in stack
    D        % convert to string and display / string representation
    w        % swap elements in stack
  ]          % end
}            % else
  I          % paste from clipboard I
  0          % number literal
  >          % is greater than? (element-wise, singleton expansion)
  ?          % if
    I        % paste from clipboard I
    :        % range; vector of equally spaced values
    "        % for
      t      % duplicate elements
    ]        % end
    x        % delete
  }          % else
    P        % flip the order of elements
    I        % paste from clipboard I
    |        % absolute value / norm / determinant
    :        % range; vector of equally spaced values
    "        % for
      t      % duplicate elements
    ]        % end
    x        % delete
             % (implicit) end
             % (implicit) end
             % (implicit) convert to string and display
```
[Answer]
## Python 3, 71 bytes
```
def f(n,s,k=1):
 if n<0:s=s[::-1];n=-n
 while n|k:print(end=s);n-=1;k=0
```
[Try it online!](https://tio.run/##BcGxCsMgFAXQPV/xyKSgoGR79k0durqXblEihttQhVDIv5tzjn/fvljGWFOmrGCaqeI1T1Qy4eG4SXszW/8JEIuJzq3siXBVPn4FXSWs0nSAFR@quJGV9c7MMT5fsx43 "Python 3 – Try It Online")
The variable `k` guarantees the loop is always run at least once. This means that if `n=0`, then `n` will be negative on the next iteration of the loop, so the loop will continue to be run forever.
[Answer]
# Matlab, 87 bytes
```
n=input('')
s=input('','s')
a=repmat(s,1,abs(n))
while~n s=[s s]
end
if n<0,flip(a)
end
```
My first attempt at code-golf! Any suggestions for golfing are welcome.
[Answer]
# [Cubix](https://github.com/ETHproductions/cubix), 41 ~~Forty four~~ ~~45~~ bytes
Takes input as *`<N> <String>`*
```
.uq.sB.p$IA;p?;ouu(..!q/o()uq?..@<w?q<<_)
```
[Try it online!](https://tio.run/##Sy5Nyqz4/1@vtFCv2EmvQMXT0brA3jq/tFRDT0@xUD9fQ7O00F5Pz8Gm3L7QxiZe8/9/XSOFkKLSkoxKAA "Cubix – Try It Online")
Cubified:
```
      . u q
      . s B
      . p $
I A ; p ? ; o u u ( . .
! q / o ( ) u q ? . . @
< w ? q < < _ ) . . . .
      . . .
      . . .
      . . .
```
[Watch it running](https://ethproductions.github.io/cubix/?code=ICAgICAgLiB1IHEKICAgICAgLiBzIEIKICAgICAgLiBwICQKSSBBIDsgcCA/IDsgbyB1IHUgKCAuIC4KISBxIC8gbyAoICkgdSBxID8gLiAuIEAKPCB3ID8gcSA8IDwgXyApIC4gLiAuIC4KICAgICAgLiAuIC4KICAgICAgLiAuIC4KICAgICAgLiAuIC4K&input=MiBIZWxsbyBXb3JsZA==&speed=20)
There is still an amount of no-ops in the code which I might be able to get a few more bytes out of, but wanted to get this up before I break it.
Basic procedure is
* `I` get counter from input
* `A` take the rest of input in as characters
* `;p?` remove the space, bring the number up and test it
	+ `psuqB$)` if the counter is negative, reverse the stack. This involves handling the input number and EOI marker(-1). Increment the counter.
	+ `;p;ouqu` if the counter is zero, remove the counter and EOI marker and start perpetual output loop.
	+ `(` if positive decrement the counter
* `<<q?/o()u` the output loop. This will output each character of the stack until the EOI marker (-1) is reached.
* `... _ ... ?wq!` on end EOI marker, go around the cube and reflect back to the `?`, change lane, drop the EOI marker to the bottom and test the counter.
* `@` if zero, halt
* `?u(` if positive u-turn and decrement, thie ends up hitting the beginning of the loop
* `? ... <)` if negative, go around the cube to the otherside, redirect to the beginning of the loop while passing over a increment.
* `/)<` if negative increment and carry on to output loop
[Answer]
# JavaScript (ES6), 79 bytes
```
 f=(n,s)=>n<0?f(-n,[...s].reverse().join``):(alert(!n?s:s.repeat(n)),!n&&f(n,s))
```
**Snippet:**
```
f=(n,s)=>n<0?f(-n,[...s].reverse().join``):(alert(!n?s:s.repeat(n)),!n&&f(n,s))
f(5, "hello world")
//f(0, "PPCG")  //uncomment this at your peril!!!
f(-2, "truThY")
f(2000, "o")
```
[Answer]
# JavaScript (ES6), ~~98~~ ~~94~~ ~~91~~ 83 bytes
```
n=>s=>{s=n<0?[...s].reverse().join``:s;while(!n)l(s);l(s.repeat(n<0?-n:n))}
```
-4, -5 bytes thanks to Arjun
-3 bytes thanks to Rick Hitchcock
Started out different than the [Java answer](https://codegolf.stackexchange.com/a/124381/65836), but quickly became very similar after golfing. Alert is infinite, but if you want it to look nice, switch to `console.log`. `l=alert;` and writing out `alert` are the same length, but if you switch to `console.log` it's shorter to redefine it.
[Answer]
## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 36 bytes
Lot ging on here, and QBIC/QBasic just doesn't have the syntax to deal with such conditions elegantly.
```
~:<0|;=_fA}[abs(a)|Z=Z+A]~a|_X}{?A';
```
Explanation:
```
~:<0|       IF cmd line arg 'a' is negative
  ;=_fA         Make cmd line arg A$ into its reverse
}           Close the IF (this eliminates the need for a | fuction terminator on _f)
[abs(a)|    FOR b = 1 to (abs(a) (hammering out negatives)
  Z=Z+A         Add A$ to Z$ (on exit, Z$ is printed explicitly)
]           NEXT
~a|_X       IF a is non-zero, terminate the program
}           END IF
{?A';       If we're here, just start a DO-loop and keep on printing the input.
```
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 137 bytes
```
void f(String[] a){for(long n=Long.valueOf(a[0]),i=0;n==0|i++<Math.abs(n);)System.out.print(n<0?new StringBuilder(a[1]).reverse():a[1]);}
```
[Try it online!](https://tio.run/##TY8xb8IwEIV3fsWNtmitMHQhREidQQyMKMNBLsGpOUe2E4TS/HZjUoa@5en0pE/ftTjgp@2I2@ondv3Z6AtcDHoPe9QMYxysrqAWx@A0N6cSUI61dcJYboCLXSo1oOnpUAs8ZaX80EWWc1Fkv3q53OwxXBWevWCZy@PDB7op2wfVJVoQvMm2THf4g3/32lTkEmZVSuVoIOdJyPV851OElLehDxhSzW635PlfD8YFvPNiv94QUiU713iZz9u0mGL8ilcyxsLdOlM9AQ "Java (OpenJDK 8) – Try It Online")
[Answer]
# [str](https://github.com/ConorOBrien-Foxx/str), 30 bytes
```
I#Lbd0<[_u_][d0='e'u#?]#?xo;db
```
[Try it online!](https://tio.run/##Ky4p@v/fU9knKcXAJjq@ND42OsXAVj1VvVTZPlbZviLfOiXp/39dIwWP1JycfB2u8PyinBRFAA "str – Try It Online")
## Explanation
```
I#Lbd0<[_u_][d0='e'u#?]#?xo;db
...........................;      preamble
I                                 read number
 #L                               read rest of STDIN
   b                              buffer the STDIN
    d                             duplicate number
     0<[   ]           #?         if the number is less than zero
        _                         negate that number
         u_                       and reverse STDIN from buffer
            [         ]           otherwise
             d0='e  #?            if its 0, push the empty string
                  'u              otherwise, push the unbuffered STDIN untouched
                         x        repeat STDIN by the TOS
                          o       and output
                           ;..    main program (only activates when input = 0)
                            d     duplicate the implicitly unbuffered STDIN
                             b    and rebuffer it
                                  implicitly displayed
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~115~~ ~~112~~ ~~109~~ ~~107~~ 104 bytes
```
f(n,s,l,p,d)char*s;{d=n<0?-1:1;do for(l=1,p=0;p>=0;p+=l)s[p]?d==l&&putchar(s[p]):l--;while(!n||(n-=d));}
```
[Try it online!](https://tio.run/##VY6xbsIwEIb3PMWVSmAXW3KidolrMiDBytClKgwoThpLV9tKQhlCnj21UVvBDTd8n/7/ruSfZTlNNbGsY8g807Rsju1TJwet7KsoeJqnUjuoXUtQpcwrIf0qrqVC2n34Q6GVwvncn/qYJBHRHDmX58ZgRR7s5UIsV5pSOU6PuqqNrWATD1IIxQPsE/id8EZh8@csKHmD/6oXe7u4ihGu3UAETRJje/g6Gku@ndEUhv/YhrwwmDUVooOza1HPqLyRIsjdbr29pzwLuG9Pb837vciEiAkX6Tj9AA "C (gcc) – Try It Online")
> 
> Who said, we need `strlen`?
> 
> 
> 
## [C (gcc)](https://gcc.gnu.org/), 115 bytes (134 with `#include<string.h>` in front)
```
#include<string.h>
f(n,s)char*s;{int l=strlen(s),d=n<0?0:2,m=d--,p;do for(p=m?0:l-1;p!=(m?l:-1);p+=d)putchar(s[p]);while(!n||(n-=d));}
```
[Try it online!](https://tio.run/##VY49b8IwFEX3/IoHDNhtXJmoXWLcDJXoytClKgwodogl59nKRxlCfnvqRG0FbzxH976bs3Oej@PKYG47pbdNWxs8P5WvUUEwbmhenuqHRvQGW7AyWKuRNDRWErc842kSV1IxFnuhHBSuJl5WAVu2EX4hSZXZlG2o8I9SUd@1Ux1pvvyRiktprCYLvF4JsmCpGMaV0oVBDbv5N4TKHg4R/F5YlGH6nAQlbvBf7fqA61kMMHcD4TSKpuHVySD5dkZR6P9jO/ISw7LU1jq4uNqqJRU3kge537@931OWBNzW3Uf5eS8SzqeEm@gw/gA "C (gcc) – Try It Online")
> 
> Without `#include<string.h>` we get an implicit prototype for `strlen` that returns `int`, but `strlen` is `size_t` (at least nowadays, not perfectly sure about k&r or c89, but I believe, it returned `int` in the old days).
> 
> 
> The missing `#include <stdio.h>` isn't a problem, because due to integer promotion, the default prototype will be `int putchar(int)` which is exactly what we want.
> 
> 
> 
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 49 bytes
```
/¶-/&V`^.+
/¶0/&//+>G0`
~`(.+)¶-*(\d+)
.-$2+>K`$1
```
Input format: takes in the string, followed by a newline, followed by the number.
[Try it online!](https://tio.run/##K0otycxLNPz/X//QNl19tbCEOD1tLiDbQF9NX1/bzt0ggasuQUNPWxMoraURk6KtyaWnq2KkbeedoALUlc9lZGBgAAA "Retina – Try It Online")
**Explanation:**
```
/¶-/&V`^.+
```
The `/¶-/&` runs this line only if the number is negative. `V` is the reverse stage, and it reverses `^.+`, which matches the string (`.` matches every character apart from newlines).
```
/¶0/&//+>G0`
```
The `/¶0/&` runs this line only if the number is 0. `//+>` starts an infinite loop, which prints the working string after each iteration. `G0` takes the string and discards the number; it does this infinitely, printing every time.
```
~`...
```
This marks code that will generate a string; the program evaluates the string as Retina code after.
```
(.+)¶-*(\d+)
.-$2+>K`$1
```
`(.+)¶-*(\d+)` matches the whole string and puts the string in capturing group 1 and the number in capturing group 2. `.-$2+>K`` `$1` generates the Retina code to be run: `.` turns implicit output off (otherwise the string would be printed n+1 times), `-$2+` sets a repeat loop that repeats for {capturing group 2} times. The minus at the beginning turns the number into a negative number, as this disables the convergence functionality in the loop, which would stop it after the 1st iteration. `>` sets this loop to print after each iteration. The rest of the code is just to print the string.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 44 bytes
```
{[$^s.flip,$s,$s Zxx-$^n,Inf,$n][$n.sign+1]}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/OlolrlgvLSezQEelGIgUoioqdFXi8nQ889J0VPJio1Xy9Ioz0/O0DWNr/xcnViqkaZjqKGWk5uTkK5TnF@WkKGlac0HEDXSUAgKc3RECukY6SiVFpSEZlQgxIwMDoLp8oMB/AA "Perl 6 – Try It Online")
Anonymous code block that takes a number and a string and returns a (possibly infinite) list
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 16 bytes
```
TaOba<0?RbbX:ABa
```
[Replit!](https://replit.com/@dloscutoff/pip) Or, here's a 17-byte equivalent in Pip Classic: [Try it online!](https://tio.run/##K8gs@P8/JNE/KdHGwD4oLCkpwsrRKfH///@m/z1Sc3LyFQE "Pip – Try It Online")
### Explanation
```
TaOba<0?RbbX:ABa
                  a and b are the two command-line arguments
Ta                Loop until a is truthy:
  Ob               Output b without a newline
                  If a=0, this loops infinitely; otherwise, it doesn't loop at all
    a<0?          If a is negative:
        Rb         b reversed
                  Else (if a is positive):
          b        b
           X:     Repeat that string this many times:
             ABa  Absolute value of a
```
]