File: 08-additional.md.html

package info (click to toggle)
lua-penlight 1.0.2%2Bhtmldoc-2
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 1,860 kB
  • sloc: makefile: 7
file content (545 lines) | stat: -rw-r--r-- 28,217 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<head>
    <title>Penlight Documentation</title>
    <link rel="stylesheet" href="../ldoc.css" type="text/css" />
</head>
<body>

<div id="container">

<div id="product">
	<div id="product_logo"></div>
	<div id="product_name"><big><b></b></big></div>
	<div id="product_description"></div>
</div> <!-- id="product" -->


<div id="main">


<!-- Menu -->

<div id="navigation">
<br/>
<h1>Penlight</h1>

<ul>
  <li><a href="../index.html">Index</a></li>
</ul>

<h2>Contents</h2>
<ul>
<li><a href="#Simple_Input_Patterns">Simple Input Patterns</a></li>
<li><a href="#Command_line_Programs_with_Lapp">Command-line Programs with Lapp</a></li>
</ul>


<h2>Topics</h2>
<ul>
  <li><a href="../topics/01-introduction.md.html">01-introduction.md</a></li>
  <li><a href="../topics/02-arrays.md.html">02-arrays.md</a></li>
  <li><a href="../topics/03-strings.md.html">03-strings.md</a></li>
  <li><a href="../topics/04-paths.md.html">04-paths.md</a></li>
  <li><a href="../topics/05-dates.md.html">05-dates.md</a></li>
  <li><a href="../topics/06-data.md.html">06-data.md</a></li>
  <li><a href="../topics/07-functional.md.html">07-functional.md</a></li>
  <li><strong>08-additional.md</strong></li>
  <li><a href="../topics/09-discussion.md.html">09-discussion.md</a></li>
</ul>
<h2>Modules</h2>
<ul>
  <li><a href="../modules/pl.html">pl</a></li>
  <li><a href="../modules/pl.Date.html">pl.Date</a></li>
  <li><a href="../modules/pl.List.html">pl.List</a></li>
  <li><a href="../modules/pl.Map.html">pl.Map</a></li>
  <li><a href="../modules/pl.MultiMap.html">pl.MultiMap</a></li>
  <li><a href="../modules/pl.OrderedMap.html">pl.OrderedMap</a></li>
  <li><a href="../modules/pl.Set.html">pl.Set</a></li>
  <li><a href="../modules/pl.app.html">pl.app</a></li>
  <li><a href="../modules/pl.array2d.html">pl.array2d</a></li>
  <li><a href="../modules/pl.class.html">pl.class</a></li>
  <li><a href="../modules/pl.comprehension.html">pl.comprehension</a></li>
  <li><a href="../modules/pl.config.html">pl.config</a></li>
  <li><a href="../modules/pl.data.html">pl.data</a></li>
  <li><a href="../modules/pl.dir.html">pl.dir</a></li>
  <li><a href="../modules/pl.file.html">pl.file</a></li>
  <li><a href="../modules/pl.func.html">pl.func</a></li>
  <li><a href="../modules/pl.input.html">pl.input</a></li>
  <li><a href="../modules/pl.lapp.html">pl.lapp</a></li>
  <li><a href="../modules/pl.lexer.html">pl.lexer</a></li>
  <li><a href="../modules/pl.luabalanced.html">pl.luabalanced</a></li>
  <li><a href="../modules/pl.operator.html">pl.operator</a></li>
  <li><a href="../modules/pl.path.html">pl.path</a></li>
  <li><a href="../modules/pl.permute.html">pl.permute</a></li>
  <li><a href="../modules/pl.pretty.html">pl.pretty</a></li>
  <li><a href="../modules/pl.seq.html">pl.seq</a></li>
  <li><a href="../modules/pl.sip.html">pl.sip</a></li>
  <li><a href="../modules/pl.strict.html">pl.strict</a></li>
  <li><a href="../modules/pl.stringio.html">pl.stringio</a></li>
  <li><a href="../modules/pl.stringx.html">pl.stringx</a></li>
  <li><a href="../modules/pl.tablex.html">pl.tablex</a></li>
  <li><a href="../modules/pl.template.html">pl.template</a></li>
  <li><a href="../modules/pl.test.html">pl.test</a></li>
  <li><a href="../modules/pl.text.html">pl.text</a></li>
  <li><a href="../modules/pl.utils.html">pl.utils</a></li>
  <li><a href="../modules/pl.xml.html">pl.xml</a></li>
</ul>
<h2>Examples</h2>
<ul>
  <li><a href="../examples/seesubst.lua.html">seesubst.lua</a></li>
  <li><a href="../examples/sipscan.lua.html">sipscan.lua</a></li>
  <li><a href="../examples/symbols.lua.html">symbols.lua</a></li>
  <li><a href="../examples/test-cmp.lua.html">test-cmp.lua</a></li>
  <li><a href="../examples/test-data.lua.html">test-data.lua</a></li>
  <li><a href="../examples/test-listcallbacks.lua.html">test-listcallbacks.lua</a></li>
  <li><a href="../examples/test-pretty.lua.html">test-pretty.lua</a></li>
  <li><a href="../examples/test-symbols.lua.html">test-symbols.lua</a></li>
  <li><a href="../examples/testapp.lua.html">testapp.lua</a></li>
  <li><a href="../examples/testclone.lua.html">testclone.lua</a></li>
  <li><a href="../examples/testconfig.lua.html">testconfig.lua</a></li>
  <li><a href="../examples/testglobal.lua.html">testglobal.lua</a></li>
  <li><a href="../examples/testinputfields.lua.html">testinputfields.lua</a></li>
  <li><a href="../examples/testinputfields2.lua.html">testinputfields2.lua</a></li>
  <li><a href="../examples/testxml.lua.html">testxml.lua</a></li>
  <li><a href="../examples/which.lua.html">which.lua</a></li>
</ul>

</div>

<div id="content">

<h1>Topic <code>08-additional.md</code></h1>

    <h2>Additional Libraries</h2>

<p>Libraries in this section are no longer considered to be part of the Penlight core, but still provide specialized functionality when needed.</p>

<p><a id="sip"/></p>

<p><a name="Simple_Input_Patterns"></a></p>

<h3>Simple Input Patterns</h3>

<p>Lua string pattern matching is very powerful, and usually you will not need a traditional regular expression library.  Even so, sometimes Lua code ends up looking like Perl, which happens because string patterns are not always the easiest things to read, especially for the casual reader.  Here is a program which needs to understand three distinct date formats:</p>

<pre>
 <span class="comment">-- parsing dates using Lua string patterns
</span> months={Jan=<span class="number">1</span>,Feb=<span class="number">2</span>,Mar=<span class="number">3</span>,Apr=<span class="number">4</span>,May=<span class="number">5</span>,Jun=<span class="number">6</span>,
 Jul=<span class="number">7</span>,Aug=<span class="number">8</span>,Sep=<span class="number">9</span>,Oct=<span class="number">10</span>,Nov=<span class="number">11</span>,Dec=<span class="number">12</span>}

 <span class="keyword">function</span> check_and_process(d,m,y)
     d = <span class="global">tonumber</span>(d)
     m = <span class="global">tonumber</span>(m)
     y = <span class="global">tonumber</span>(y)
     ....
 <span class="keyword">end</span>

 <span class="keyword">for</span> line <span class="keyword">in</span> f:lines() <span class="keyword">do</span>
     <span class="comment">-- ordinary (English) date format
</span>     <span class="keyword">local</span> d,m,y = line:match(<span class="string">'(%d+)/(%d+)/(%d+)'</span>)
     <span class="keyword">if</span> d <span class="keyword">then</span>
         check_and_process(d,m,y)
     <span class="keyword">else</span> <span class="comment">-- ISO date??
</span>         y,m,d = line:match(<span class="string">'(%d+)%-(%d+)%-(%d+)'</span>)
         <span class="keyword">if</span> y <span class="keyword">then</span>
             check_and_process(d,m,y)
         <span class="keyword">else</span> <span class="comment">-- &lt;day&gt; &lt;month-name&gt; &lt;year&gt;?
</span>             d,mm,y = line:match(<span class="string">'%(d+)%s+(%a+)%s+(%d+)'</span>)
             m = months[mm]
             check_and_process(d,m,y)
         <span class="keyword">end</span>
     <span class="keyword">end</span>
 <span class="keyword">end</span>
</pre>


<p>These aren&rsquo;t particularly difficult patterns, but already typical issues are appearing, such as having to escape &lsquo;&ndash;&rsquo;. Also, <a href="http://www.lua.org/manual/5.1/manual.html#pdf-string.match">string.match</a>  returns its captures, so that we're forced to use a slightly awkward nested if-statement.</p>

<p>Verification issues will further cloud the picture, since regular expression people try to enforce constraints (like year cannot be more than four digits) using regular expressions, on the usual grounds that one shouldn&rsquo;t stop using a hammer when one is enjoying oneself.</p>

<p><a href="../modules/pl.sip.html#">pl.sip</a>  provides a simple, intuitive way to detect patterns in strings and extract relevant parts.</p>

<pre>
 &gt; sip = <span class="global">require</span> <span class="string">'pl.sip'</span>
 &gt; dump = <span class="global">require</span>(<span class="string">'pl.pretty'</span>).dump
 &gt; res = {}
 &gt; c = sip.compile <span class="string">'ref=$S{file}:$d{line}'</span>
 &gt; = c(<span class="string">'ref=hello.c:10'</span>,res)
 <span class="keyword">true</span>
 &gt; dump(res)
 {
   line = <span class="number">10</span>,
   file = <span class="string">"hello.c"</span>
 }
 &gt; = c(<span class="string">'ref=long name, no line'</span>,res)
 <span class="keyword">false</span>
</pre>


<p><a href="../modules/pl.sip.html#compile">sip.compile</a>  creates a pattern matcher function, which is given a string and a table. If it matches the string, then <code>true</code> is returned and the table is populated according to the <em>named fields</em> in the pattern.</p>

<p>Here is another version of the date parser:</p>

<pre>
 <span class="comment">-- using SIP patterns
</span> <span class="keyword">function</span> check(t)
     check_and_process(t.day,t.month,t.year)
 <span class="keyword">end</span>

 shortdate = sip.compile(<span class="string">'$d{day}/$d{month}/$d{year}'</span>)
 longdate = sip.compile(<span class="string">'$d{day} $v{mon} $d{year}'</span>)
 isodate = sip.compile(<span class="string">'$d{year}-$d{month}-$d{day}'</span>)

 <span class="keyword">for</span> line <span class="keyword">in</span> f:lines() <span class="keyword">do</span>
     <span class="keyword">local</span> res = {}
     <span class="keyword">if</span> shortdate(str,res) <span class="keyword">then</span>
         check(res)
     <span class="keyword">elseif</span> isodate(str,res) <span class="keyword">then</span>
         check(res)
     <span class="keyword">elseif</span> longdate(str,res) <span class="keyword">then</span>
         res.month = months[res.mon]
         check(res)
     <span class="keyword">end</span>
 <span class="keyword">end</span>
</pre>


<p>SIP patterns start with &lsquo;$&rsquo;, then a one-letter type, and then an optional variable in curly braces.</p>

<pre>
 Type    Meaning
 v         variable, <span class="keyword">or</span> identifier.
 i          possibly signed integer
 f          floating-point number
 r          <span class="string">'rest of line'</span>
 q         quoted <span class="global">string</span> (either ' <span class="keyword">or</span> ")
 p         a path name
 (         anything inside (...)
 [         anything inside [...]
 {         anything inside {...}
 &lt;         anything inside &lt;...&gt;
 [<span class="comment">---------------------------------]
</span> S         non-space
 d         digits
 ...
</pre>


<p>If a type is not one of v,i,f,r or q, then it&rsquo;s assumed to be one of the standard Lua character classes.  Any spaces you leave in your pattern will match any number of spaces.  And any &lsquo;magic&rsquo; string characters will be escaped.</p>

<p>SIP captures (like <code>$v{mon}</code>) do not have to be named. You can use just <code>$v</code>, but you have to be consistent; if a pattern contains unnamed captures, then all captures must be unnamed. In this case, the result table is a simple list of values.</p>

<p><a href="../modules/pl.sip.html#match">sip.match</a>  is a useful shortcut if you like your matches to be &lsquo;in place&rsquo;. (It caches the result, so it is not much slower than explicitly using <a href="../modules/pl.sip.html#compile">sip.compile</a> .)</p>

<pre>
 &gt; sip.match(<span class="string">'($q{first},$q{second})'</span>,<span class="string">'("john","smith")'</span>,res)
 <span class="keyword">true</span>
 &gt; res
 {second=<span class="string">'smith'</span>,first=<span class="string">'john'</span>}
 &gt; res = {}
 &gt; sip.match(<span class="string">'($q,$q)'</span>,<span class="string">'("jan","smit")'</span>,res)  <span class="comment">-- unnamed captures
</span> <span class="keyword">true</span>
 &gt; res
 {<span class="string">'jan'</span>,<span class="string">'smit'</span>}
 &gt; sip.match(<span class="string">'($q,$q)'</span>,<span class="string">'("jan", "smit")'</span>,res)
 <span class="keyword">false</span>   <span class="comment">---&gt; oops! Can't handle extra space!
</span> &gt; sip.match(<span class="string">'( $q , $q )'</span>,<span class="string">'("jan", "smit")'</span>,res)
 <span class="keyword">true</span>
</pre>


<p>As a general rule, allow for whitespace in your patterns.</p>

<p>Finally, putting a &lsquo; $&rsquo; at the end of a pattern means &lsquo;capture the rest of the line, starting at the first non-space&rsquo;.</p>

<pre>
 &gt; sip.match(<span class="string">'( $q , $q ) $'</span>,<span class="string">'("jan", "smit") and a string'</span>,res)
 <span class="keyword">true</span>
 &gt; res
 {<span class="string">'jan'</span>,<span class="string">'smit'</span>,<span class="string">'and a string'</span>}
 &gt; res = {}
 &gt; sip.match(<span class="string">'( $q{first} , $q{last} ) $'</span>,<span class="string">'("jan", "smit") and a string'</span>,res)
 <span class="keyword">true</span>
 &gt; res
 {first=<span class="string">'jan'</span>,rest=<span class="string">'and a string'</span>,last=<span class="string">'smit'</span>}
</pre>


<p><a id="lapp"/></p>

<p><a name="Command_line_Programs_with_Lapp"></a></p>

<h3>Command-line Programs with Lapp</h3>

<p><a href="../modules/pl.lapp.html#">pl.lapp</a>  is a small and focused Lua module which aims to make standard command-line parsing easier and intuitive. It implements the standard GNU style, i.e. short flags with one letter start with &lsquo;&ndash;&rsquo;, and there may be an additional long flag which starts with &lsquo;&mdash;&rsquo;. Generally options which take an argument expect to find it as the next parameter (e.g. &lsquo;gcc test.c -o test&rsquo;) but single short options taking a numerical parameter can dispense with the space (e.g. &lsquo;head -n4 test.c&rsquo;)</p>

<p>As far as possible, Lapp will convert parameters into their equivalent Lua types, i.e. convert numbers and convert filenames into file objects. If any conversion fails, or a required parameter is missing, an error will be issued and the usage text will be written out. So there are two necessary tasks, supplying the flag and option names and associating them with a type.</p>

<p>For any non-trivial script, even for personal consumption, it&rsquo;s necessary to supply usage text. The novelty of Lapp is that it starts from that point and defines a loose format for usage strings which can specify the names and types of the parameters.</p>

<p>An example will make this clearer:</p>

<pre>
 <span class="comment">-- scale.lua
</span>   lapp = <span class="global">require</span> <span class="string">'pl.lapp'</span>
   <span class="keyword">local</span> args = lapp <span class="string">[[
   Does some calculations
     -o,--offset (default 0.0)  Offset to add to scaled number
     -s,--scale  (number)  Scaling factor
      &lt;number&gt; (number )  Number to be scaled
   ]]</span>

   <span class="global">print</span>(args.offset + args.scale * args.number)
</pre>


<p>Here is a command-line session using this script:</p>

<pre>
 $ lua scale.lua
 scale.lua:missing required parameter: scale

 Does some calculations
  -o,<span class="comment">--offset (default 0.0)  Offset to add to scaled number
</span>  -s,<span class="comment">--scale  (number)  Scaling factor
</span>   &lt;number&gt; (number )  Number to be scaled

 $ lua scale.lua -s <span class="number">2.2</span> <span class="number">10</span>
 <span class="number">22</span>

 $ lua scale.lua -s <span class="number">2.2</span> x10
 scale.lua:unable to convert to number: x10

 ....(usage as before)
</pre>


<p>There are two kinds of lines in Lapp usage strings which are meaningful; option and parameter lines. An option line gives the short option, optionally followed by the corresponding long option. A type specifier in parentheses may follow. Similarly, a parameter line starts with &lsquo;&lt;&rsquo; PARAMETER &lsquo;>&rsquo;, followed by a type specifier. Type specifiers are either of the form &lsquo;(default &rsquo; VALUE &lsquo;)&rsquo; or &lsquo;(&rsquo; TYPE &lsquo;)&rsquo;; the default specifier means that the parameter or option has a default value and is not required. TYPE is one of &lsquo;string&rsquo;,&lsquo;number&rsquo;,&lsquo;file-in&rsquo; or &lsquo;file-out&rsquo;; VALUE is a number, one of (&lsquo;stdin&rsquo;,&lsquo;stdout&rsquo;,&lsquo;stderr&rsquo;) or a token. The rest of the line is not parsed and can be used for explanatory text.</p>

<p>This script shows the relation between the specified parameter names and the fields in the output table.</p>

<pre>
 <span class="comment">-- simple.lua
</span> <span class="keyword">local</span> args = <span class="global">require</span> (<span class="string">'pl.lapp'</span>) <span class="string">[[
 Various flags and option types
   -p          A simple optional flag, defaults to false
   -q,--quiet  A simple flag with long name
   -o  (string)  A required option with argument
   &lt;input&gt; (default stdin)  Optional input file parameter
 ]]</span>

 <span class="keyword">for</span> k,v <span class="keyword">in</span> <span class="global">pairs</span>(args) <span class="keyword">do</span>
     <span class="global">print</span>(k,v)
 <span class="keyword">end</span>
</pre>


<p>I've just dumped out all values of the args table; note that args.quiet has become true, because it&rsquo;s specified; args.p defaults to false. If there is a long name for an option, that will be used in preference as a field name. A type or default specifier is not necessary for simple flags, since the default type is boolean.</p>

<pre>
 $ simple -o test -q simple.lua
 p       <span class="keyword">false</span>
 input   file (<span class="number">781</span>C1BD8)
 quiet   <span class="keyword">true</span>
 o       test
 input_name      simple.lua
 D:\dev\lua\lapp&gt;simple -o test simple.lua one two three
 <span class="number">1</span>       one
 <span class="number">2</span>       two
 <span class="number">3</span>       three
 p       <span class="keyword">false</span>
 quiet   <span class="keyword">false</span>
 input   file (<span class="number">781</span>C1BD8)
 o       test
 input_name      simple.lua
</pre>


<p>The parameter input has been set to an open read-only file object &ndash; we know it must be a read-only file since that is the type of the default value. The field input_name is automatically generated, since it&rsquo;s often useful to have access to the original filename.</p>

<p>Notice that any extra parameters supplied will be put in the result table with integer indices, i.e. args[i] where i goes from 1 to #args.</p>

<p>Files don&rsquo;t really have to be closed explicitly for short scripts with a quick well-defined mission, since the result of garbage-collecting file objects is to close them.</p>

<h4>Enforcing a Range for a Parameter</h4>

<p>The type specifier can also be of the form &lsquo;(&rsquo; MIN &lsquo;..&rsquo; MAX &lsquo;)&rsquo;.</p>

<pre>
 <span class="keyword">local</span> lapp = <span class="global">require</span> <span class="string">'pl.lapp'</span>
 <span class="keyword">local</span> args = lapp <span class="string">[[
     Setting ranges
     &lt;x&gt; (1..10)  A number from 1 to 10
     &lt;y&gt; (-5..1e6) Bigger range
 ]]</span>

 <span class="global">print</span>(args.x,args.y)
</pre>


<p>Here the meaning is that the value is greater or equal to MIN and less or equal to MAX; there is no provision for forcing a parameter to be a whole number.</p>

<p>You may also define custom types that can be used in the type specifier:</p>

<pre>
 lapp = <span class="global">require</span> (<span class="string">'pl.lapp'</span>)

 lapp.add_type(<span class="string">'integer'</span>,<span class="string">'number'</span>,
     <span class="keyword">function</span>(x)
         lapp.<span class="global">assert</span>(<span class="global">math</span>.ceil(x) == x, <span class="string">'not an integer!'</span>)
     <span class="keyword">end</span>
 )

 <span class="keyword">local</span> args =  lapp <span class="string">[[
     &lt;ival&gt; (integer) Process PID
 ]]</span>

 <span class="global">print</span>(args.ival)
</pre>


<p><a href="../modules/pl.lapp.html#add_type">lapp.add_type</a>  takes three parameters, a type name, a converter and a constraint function. The constraint function is expected to throw an assertion if some condition is not true; we use lapp.assert because it fails in the standard way for a command-line script. The converter argument can either be a type name known to Lapp, or a function which takes a string and generates a value.</p>

<h4>&lsquo;varargs&rsquo; Parameter Arrays</h4>

<pre>
 lapp = <span class="global">require</span> <span class="string">'pl.lapp'</span>
 <span class="keyword">local</span> args = lapp <span class="string">[[
 Summing numbers
     &lt;numbers...&gt; (number) A list of numbers to be summed
 ]]</span>

 <span class="keyword">local</span> sum = <span class="number">0</span>
 <span class="keyword">for</span> i,x <span class="keyword">in</span> <span class="global">ipairs</span>(args.numbers) <span class="keyword">do</span>
     sum = sum + x
 <span class="keyword">end</span>
 <span class="global">print</span> (<span class="string">'sum is '</span>..sum)
</pre>


<p>The parameter number has a trailing &lsquo;&hellip;&rsquo;, which indicates that this parameter is a &lsquo;varargs&rsquo; parameter. It must be the last parameter, and args.number will be an array.</p>

<p>Consider this implementation of the head utility from Mac OS X:</p>

<pre>
 <span class="comment">-- implements a BSD-style head
</span> <span class="comment">-- (see http://www.manpagez.com/man/1/head/osx-10.3.php)
</span>
 lapp = <span class="global">require</span> (<span class="string">'pl.lapp'</span>)

 <span class="keyword">local</span> args = lapp <span class="string">[[
 Print the first few lines of specified files
    -n         (default 10)    Number of lines to print
    &lt;files...&gt; (default stdin) Files to print
 ]]</span>

 <span class="comment">-- by default, lapp converts file arguments to an actual Lua file object.
</span> <span class="comment">-- But the actual filename is always available as &lt;file&gt;_name.
</span> <span class="comment">-- In this case, 'files' is a varargs array, so that 'files_name' is
</span> <span class="comment">-- also an array.
</span> <span class="keyword">local</span> nline = args.n
 <span class="keyword">local</span> nfile = #args.files
 <span class="keyword">for</span> i = <span class="number">1</span>,nfile <span class="keyword">do</span>
     <span class="keyword">local</span> file = args.files[i]
     <span class="keyword">if</span> nfile &gt; <span class="number">1</span> <span class="keyword">then</span>
         <span class="global">print</span>(<span class="string">'==&gt; '</span>..args.files_name[i]..<span class="string">' &lt;=='</span>)
     <span class="keyword">end</span>
     <span class="keyword">local</span> n = <span class="number">0</span>
     <span class="keyword">for</span> line <span class="keyword">in</span> file:lines() <span class="keyword">do</span>
         <span class="global">print</span>(line)
         n = n + <span class="number">1</span>
         <span class="keyword">if</span> n == nline <span class="keyword">then</span> <span class="keyword">break</span> <span class="keyword">end</span>
     <span class="keyword">end</span>
 <span class="keyword">end</span>
</pre>


<p>Note how we have access to all the filenames, because the auto-generated field <code>files_name</code> is also an array!</p>

<p>(This is probably not a very considerate script, since Lapp will open all the files provided, and only close them at the end of the script. See the <code>xhead.lua</code> example for another implementation.)</p>

<p>Flags and options may also be declared as vararg arrays, and can occur anywhere. Bear in mind that short options can be combined (like &lsquo;tar -xzf&rsquo;), so it&rsquo;s perfectly legal to have &lsquo;-vvv&rsquo;. But normally the value of args.v is just a simple <code>true</code> value.</p>

<pre>
 <span class="keyword">local</span> args = <span class="global">require</span> (<span class="string">'pl.lapp'</span>) <span class="string">[[
    -v...  Verbosity level; can be -v, -vv or -vvv
 ]]</span>
 vlevel = <span class="keyword">not</span> args.v[<span class="number">1</span>] <span class="keyword">and</span> <span class="number">0</span> <span class="keyword">or</span> #args.v
 <span class="global">print</span>(vlevel)
</pre>


<p>The vlevel assigment is a bit of Lua voodoo, so consider the cases:</p>

<pre>
 * No -v flag, v is just { <span class="keyword">false</span> }
 * One -v flags, v is { <span class="keyword">true</span> }
 * Two -v flags, v is { <span class="keyword">true</span>, <span class="keyword">true</span> }
 * Three -v flags, v is { <span class="keyword">true</span>, <span class="keyword">true</span>, <span class="keyword">true</span> }
</pre>


<h4>Defining a Parameter Callback</h4>

<p>If a script implements <code>lapp.callback</code>, then Lapp will call it after each argument is parsed. The callback is passed the parameter name, the raw unparsed value, and the result table. It is called immediately after assignment of the value, so the corresponding field is available.</p>

<pre>
 lapp = <span class="global">require</span> (<span class="string">'pl.lapp'</span>)

 <span class="keyword">function</span> lapp.callback(parm,arg,args)
     <span class="global">print</span>(<span class="string">'+'</span>,parm,arg)
 <span class="keyword">end</span>

 <span class="keyword">local</span> args = lapp <span class="string">[[
 Testing parameter handling
     -p               Plain flag (defaults to false)
     -q,--quiet       Plain flag with GNU-style optional long name
     -o  (string)     Required string option
     -n  (number)     Required number option
     -s (default 1.0) Option that takes a number, but will default
     &lt;start&gt; (number) Required number argument
     &lt;input&gt; (default stdin)  A parameter which is an input file
     &lt;output&gt; (default stdout) One that is an output file
 ]]</span>
 <span class="global">print</span> <span class="string">'args'</span>
 <span class="keyword">for</span> k,v <span class="keyword">in</span> <span class="global">pairs</span>(args) <span class="keyword">do</span>
     <span class="global">print</span>(k,v)
 <span class="keyword">end</span>
</pre>


<p>This produces the following output:</p>

<pre>
 $ args -o name -n <span class="number">2</span> <span class="number">10</span> args.lua
 +       o       name
 +       n       <span class="number">2</span>
 +       start   <span class="number">10</span>
 +       input   args.lua
 args
 p       <span class="keyword">false</span>
 s       <span class="number">1</span>
 input_name      args.lua
 quiet   <span class="keyword">false</span>
 output  file (<span class="number">781</span>C1B98)
 start   <span class="number">10</span>
 input   file (<span class="number">781</span>C1BD8)
 o       name
 n       <span class="number">2</span>
</pre>


<p>Callbacks are needed when you want to take action immediately on parsing an argument.</p>


</div> <!-- id="content" -->
</div> <!-- id="main" -->
<div id="about">
<i>generated by <a href="http://github.com/stevedonovan/LDoc">LDoc 1.2</a></i>
</div> <!-- id="about" -->
</div> <!-- id="container" -->
</body>
</html>