Something like charIndex, but in a variable...
Ben Rubinstein
benr_mc at cogapp.com
Thu Apr 30 11:50:06 EDT 2015
On 30/04/2015 09:07, Malte Brill wrote:
> I need to find the start and end character of chuncks in a variable. If we are in a field we can use charIndex for that. However, in a variable I have no good idea on how to do something similar to
>
> get charIndex(token 7 of line 15 of field „myField“)
(unhelpful to Malte, sorry) - I hadn't noticed the introduction of charIndex.
What a useful property. It would be great if it could be extended to
arbitrary sources of value.
In the meantime, could one write an ugly function to calculate the start index
of a chunk by first getting the length of the preceeding chunks, then using
that value as the charsToSkip for a call to offset on the value of the chunk?
So a first approximation - it would need some better work parsing the chunk
expression to be robust -
function chunkIndex tFullChunkExpr, tValue
local tChunkExpr, tPriorChunksExpr, tChunkValue, iConsumed, n, i
-- convert nested chunk expression into lines, minor to major
replace " of " with return in tFullChunkExpr
if last word of tFullChunkExpr = "of" then \
delete last word of tFullChunkExpr
-- accumulate start of each level of chunk
put 0 into iConsumed
-- find the start of each chunk in the expression, from major to minor
repeat with i = number of lines in tFullChunkExpr down to 1
put line i of tFullChunkExpr into tChunkExpr
-- make an expression for the chunks prior to this one
put tChunkExpr into tPriorChunksExpr
put format("1 to %d", word 2 of tChunkExpr - 1) \
into word 2 of tPriorChunksExpr
-- get the length of the chunks prior to this one
do format("put length(%s of tValue) into n", tPriorChunksExpr)
-- get this chunk, and find the first instance
-- of it after the length of the prior chunks
do ("put" && tChunkExpr && "of tValue into tChunkValue")
add offset(tChunkValue, tValue, n) + n to iConsumed
-- repeat within this chunk
put tChunkValue into tValue
end repeat
return iConsumed - 1
end chunkIndex
To be called as e.g.
get chunkIndex("token 7 of line 15 of", myVar)
I suspect that this could be fooled if there was a lot of leading white space
(and a repetition of the target chunk prior to it), but that could probably be
dealt with by an additional check for offset of the 'priorChunkValue'.
Ben
More information about the use-livecode
mailing list