Suppose you have a textfile containing various numbers and you want to add them up. For the purposes of identification suppose each number is preceded by the character @ . To sum the numbers in StrongED you can use this script:
#! lua
local sum = 0
for line in io.lines (arg[1]) do
line:gsub ("@(%d+)", \ (x) sum += tonumber (x) end)
end -- for
print (sum)
The string-method gsub has a variety of uses. It scans the string for
the pattern given by its first argument, capturing the substrings indicated
by parentheses and feeding them to the function given by its second
argument. We can also use a table for the second argument.
Suppose we need to do a mail-merge. That is to say we have a standard letter containing parts that vary. Again we use the symbol @ to prefix variable names to be evaluated later. For example:
Dear @person
You forgot your @item at the party last night.
I will send it on tomorrow.
Yours sincerely
Goofy
We modify this to
#! lua
local fillin = dofile (arg[1])
local letter = [[ Dear @person
You forgot your @item at the party last night.
I will send it on tomorrow.
Yours sincerely
Goofy]]
os.write (letter:gsub ("@([%w_]+)", fillin))
Then open lots of StrongED windows like this:
=> { person = "Mickey"; item = "frisbee"; }
If you SHIFT-CTL-drag the modified letter to the apply icon of one
these windows then each one will be replaced by the corresponding filled in
letter, ready for emailing, printing, saving, etc.