# valid_index

Definition: | bool res = valid_index(sequence s, object idx)
Description: | Simple check whether idx can legally be used to subscript s. Should this routine return false, attempts to do so would raise an exception (probably2). s: the sequence for which the index is to be checked. idx: the proposed subscript. Negative subscripts are supported, idx is checked to be an integer in the range 1 to length(s) or it’s negative counterpart (which subscripts right/last to left/first). Note that while Euphoria allows fractional subscripts (truncating them), Phix does not1, forcing you to either truncate or round them as appropriate first, since it would rather not guess and (at least sometimes, and possibly more often given Phix permits -ve idx whereas Eu does not) inevitably be wrong. 1 Currently rather weakly/sporadically enforced in 1.x2, will be more strictly prohibited in 2.x - one thing earmarked for improvement is subscript performance, and if not permitting fractional indices helps in any way (speed / less ARM assembly / less testing), I’m taking it. Genrerally speaking, subscripts in Phix are fine and pretty fast, and not something you should try and avoid, it’s just that some other languages do them better, in particular those that only permit homogenous arrays (and as it happens only integer subscripts). In fact, subscripting in Phix already seriously outperforms that in say JavaScript and Python. The two planned improvements are: a) spot when a sequence is or can be flagged as homogenous, and b) better register allocation, and should I want to put a subscript in a CPU register, for any gain it’d jolly well better be an integer. 2 For an example, s[i/3] (when i is 4) tends to blow up, whereas s[1.333] doesn’t - which can hardly be described as consistent behaviour, and is clearly something 2.x should address. Obviously a calculated subscript of 1.333 strongly suggests a logic error in the code.
pwa/p2js: | Supported.
Implementation: | See builtins\pseqc.e (an autoinclude) for details of the actual implementation (which is pretty trivial, but sometimes quite handy).