Scripting
Dragging
arg[1]whose value should be treated as a filename. The new contents of the StrongED window is created by the script's output, typically using the functions
print io.writeConsider this script:
#! lua
local n, inc = 10, 10
for line in io.lines (arg[1]) do
print (n, line)
n += inc
end -- for
This numbers the lines starting at 10, with increments of 10.
The io.lines iterator is very useful and concise but it
can only be used if the data your script is supposed to capture
always lies on a single line. If the data extends over many lines
it may be more convenient to read in the whole text as a single string
as in this example.
#!lua
-- Print the phrases beginning Hello and ending Dolly.
local input, read in io
input (arg[1]) -- switch input to arg[1]
local text = read "*all"
input ( ) -- reset back to stdin
for phrase in text:gmatch "(Hello.-Dolly)" do
print (phrase)
end -- for
The point is that when you find Hello you do not know how many
further lines to search for a Dolly , which would make the line by line
approach rather clumsy.
Before you write any code, you should consider which approach to adopt:
line by line with io.lines , or read in the whole text with io.read .
As a matter of style note the use of local variables wherever possible,
so that an item in a library is only looked up once at most.
Avoiding performing the same calculation twice, if necessary by creating more variables, should be an instinct.