Why the label output is NaN in the following code?
//@version=5
indicator("My script")
if barstate.islast
ema = ta.ema(close, 21)
label.new(bar_index, 0, str.tostring(ema[bar_index]))
plot(close)
Taking into account both of these points, the calculation of the amount will occur only when a conditional block is hit, and since hits may not occur on every bar, the amount will be distorted (when calculating, the previous historical value will be subtracted, it may turn out that it was many bars ago). Therefore, such functions are more reliably called outside of conditional blocks. But if you calculate it only once on the last bar, then the second point will not create problems. Only the first one, because you do not have a historical EMA value on the first bar, because your script did not calculate the EMA on the first bar.
It is described in official Pine manual https://www.tradingview.com/pine-script-docs/en/v5/language/Execution_model.html#historical-values-of-functions