File: 03-strings.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 (340 lines) | stat: -rw-r--r-- 16,680 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
<!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="#Extra_String_Methods">Extra String Methods</a></li>
<li><a href="#String_Templates">String Templates</a></li>
<li><a href="#Another_Style_of_Template">Another Style of Template</a></li>
<li><a href="#File_style_I_O_on_Strings">File-style I/O on Strings</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><strong>03-strings.md</strong></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><a href="../topics/08-additional.md.html">08-additional.md</a></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>03-strings.md</code></h1>

    <h2>Strings. Higher-level operations on strings.</h2>

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

<h3>Extra String Methods</h3>

<p>These are convenient borrowings from Python, as described in 3.6.1 of the Python reference, but note that indices in Lua always begin at one. <a href="../modules/pl.stringx.html#">stringx</a>  defines functions like <a href="../modules/pl.stringx.html#isalpha">isalpha</a>  and <a href="../modules/pl.stringx.html#isdigit">isdigit</a> , which return <code>true</code> if s is only composed of letters or digits respectively. <a href="../modules/pl.stringx.html#startswith">startswith</a>  and <a href="../modules/pl.stringx.html#endswith">endswith</a>  are convenient ways to find substrings. (<a href="../modules/pl.stringx.html#endswith">endswith</a>  works as in Python 2.5, so that <code>f:endswith {'.bat','.exe','.cmd'}</code> will be true for any filename which ends with these extensions.) There are justify methods and whitespace trimming functions like <a href="../modules/pl.stringx.html#strip">strip</a> .</p>

<pre>
 &gt; stringx.import()
 &gt; (<span class="string">'bonzo.dog'</span>):endswith {<span class="string">'.dog'</span>,<span class="string">'.cat'</span>}
 <span class="keyword">true</span>
 &gt; (<span class="string">'bonzo.txt'</span>):endswith {<span class="string">'.dog'</span>,<span class="string">'.cat'</span>}
 <span class="keyword">false</span>
 &gt; (<span class="string">'bonzo.cat'</span>):endswith {<span class="string">'.dog'</span>,<span class="string">'.cat'</span>}
 <span class="keyword">true</span>
 &gt; (<span class="string">' stuff'</span>):ljust(<span class="number">20</span>,<span class="string">'+'</span>)
 <span class="string">'++++++++++++++ stuff'</span>
 &gt; (<span class="string">'  stuff '</span>):lstrip()
 <span class="string">'stuff '</span>
 &gt; (<span class="string">'  stuff '</span>):rstrip()
 <span class="string">'  stuff'</span>
 &gt; (<span class="string">'  stuff '</span>):strip()
 <span class="string">'stuff'</span>
 &gt; <span class="keyword">for</span> s <span class="keyword">in</span> (<span class="string">'one\ntwo\nthree\n'</span>):lines() <span class="keyword">do</span> <span class="global">print</span>(s) <span class="keyword">end</span>
 one
 two
 three
</pre>


<p>Most of these can be fairly easily implemented using the Lua string library, which is more general and powerful. But they are convenient operations to have easily at hand. Note that can be injected into the <a href="http://www.lua.org/manual/5.1/manual.html#5.4">string</a>  table if you use <code>stringx.import</code>, but a simple alias like <code>local stringx = require 'pl.stringx'</code> is preferrable. This is the recommended practice when writing modules for consumption by other people, since it is bad manners to change the global state of the rest of the system.</p>

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

<h3>String Templates</h3>

<p>Another borrowing from Python, string templates allow you to substitute values looked up in a table:</p>

<pre>
 <span class="keyword">local</span> Template = <span class="global">require</span> (<span class="string">'pl.text'</span>).Template
 t = Template(<span class="string">'${here} is the $answer'</span>)
 <span class="global">print</span>(t:substitute {here = <span class="string">'Lua'</span>, answer = <span class="string">'best'</span>})
 ==&gt;
 Lua is the best
</pre>


<p>&lsquo;$ variables&rsquo; can optionally have curly braces; this form is useful if you are glueing text together to make variables, e.g <code>${prefix}_name_${postfix}</code>. The <code>substitute</code> method will throw an error if a $ variable is not found in the table, and the <code>safe_substitute</code> method will not.</p>

<p>The Lua implementation has an extra method, <code>indent_substitute</code> which is very useful for inserting blocks of text, because it adjusts indentation. Consider this example:</p>

<pre>
 <span class="comment">-- testtemplate.lua
</span> <span class="keyword">local</span> Template = <span class="global">require</span> (<span class="string">'pl.text'</span>).Template

 t = Template <span class="string">[[
     for i = 1,#$t do
         $body
     end
 ]]</span>

 body = Template <span class="string">[[
 local row = $t[i]
 for j = 1,#row do
     fun(row[j])
 end
 ]]</span>

 <span class="global">print</span>(t:indent_substitute {body=body,t=<span class="string">'tbl'</span>})
</pre>


<p>And the output is:</p>

<pre>
 <span class="keyword">for</span> i = <span class="number">1</span>,#tbl <span class="keyword">do</span>
     <span class="keyword">local</span> row = tbl[i]
     <span class="keyword">for</span> j = <span class="number">1</span>,#row <span class="keyword">do</span>
         fun(row[j])
     <span class="keyword">end</span>
 <span class="keyword">end</span>
</pre>


<p><code>indent_substitute</code> can substitute templates, and in which case they themselves will be substituted using the given table. So in this case, <code>$t</code> was substituted twice.</p>

<p><a href="../modules/pl.text.html#">pl.text</a>  also has a number of useful functions like <a href="../modules/pl.text.html#dedent">dedent</a> , which strips all the initial indentation from a multiline string. As in Python, this is useful for preprocessing multiline strings if you like indenting them with your code. The function <a href="../modules/pl.text.html#wrap">wrap</a>  is passed a long string (a <em>paragraph</em>) and returns a list of lines that fit into a desired line width. As an extension, there is also <a href="../modules/pl.text.html#indent">indent</a>  for indenting multiline strings.</p>

<p>New in Penlight with the 0.9 series is <a href="../modules/pl.text.html#format_operator">text.format_operator</a> . Calling this enables Python-style string formating using the modulo operator <code>%</code>:</p>

<pre>
 &gt; text.format_operator()
 &gt; = <span class="string">'%s[%d]'</span> % {<span class="string">'dog'</span>,<span class="number">1</span>}
 dog[<span class="number">1</span>]
</pre>


<p>So in its simplest form it saves the typing involved with <a href="http://www.lua.org/manual/5.1/manual.html#pdf-string.format">string.format</a> ; it will also expand <code>$</code> variables using named fields:</p>

<pre>
 &gt; = <span class="string">'$animal[$num]'</span> % {animal=<span class="string">'dog'</span>,num=<span class="number">1</span>}
 dog[<span class="number">1</span>]
</pre>


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

<h3>Another Style of Template</h3>

<p>A new module is <a href="../modules/pl.template.html#">template</a> , which is a version of Rici Lake&rsquo;s <a href="http://lua-users.org/wiki/SlightlyLessSimpleLuaPreprocessor">Lua  Preprocessor</a>.  This allows you to mix Lua code with your templates in a straightforward way. There are only two rules:</p>

<ul>
<li>Lines begining with <code>#</code> are Lua</li>
<li>Otherwise, anything inside <code>$()</code> is a Lua expression.</li>
</ul>


<p>So a template generating an HTML list would look like this:</p>

<pre>
 &lt;ul&gt;
 # <span class="keyword">for</span> i,val <span class="keyword">in</span> <span class="global">ipairs</span>(T) <span class="keyword">do</span>
 &lt;li&gt;$(i) = $(val:upper())&lt;/li&gt;
 # <span class="keyword">end</span>
 &lt;/ul&gt;
</pre>


<p>Assume the text is inside <code>tmpl</code>, then the template can be expanded using:</p>

<pre>
 <span class="keyword">local</span> template = <span class="global">require</span> <span class="string">'pl.template'</span>
 res = template.substitute(tmpl,{T = {<span class="string">'one'</span>,<span class="string">'two'</span>,<span class="string">'three'</span>}})
</pre>


<p>and we get</p>

<pre>
 &lt;ul&gt;
 &lt;li&gt;<span class="number">1</span> = ONE&lt;/li&gt;
 &lt;li&gt;<span class="number">2</span> = TWO&lt;/li&gt;
 &lt;li&gt;<span class="number">3</span> = THREE&lt;/li&gt;
 &lt;/ul&gt;
</pre>


<p>There is a single function, <a href="../modules/pl.template.html#substitute">template.substitute</a>  which is passed a template string and an environment table.   This table may contain some special fields, like <code>_parent</code> which can be set to a table representing a &lsquo;fallback&rsquo; environment in case a symbol was not found. <code>_brackets</code> is usually &lsquo;()&rsquo; and <code>_escape</code> is usually &lsquo;#&rsquo; but it&rsquo;s sometimes necessary to redefine these if the defaults interfere with the target language &ndash; for instance, <code>$(V)</code> has another meaning in Make, and <code>#</code> means a preprocessor line in C/C++.</p>

<p>Finally, if something goes wrong, passing <code>_debug</code> will cause the intermediate Lua code to be dumped if there&rsquo;s a problem.</p>

<p>Here is a C code generation example; something that could easily be extended to be a minimal Lua extension skeleton generator.</p>

<pre>
 <span class="keyword">local</span> subst = <span class="global">require</span> <span class="string">'pl.template'</span>.substitute

 <span class="keyword">local</span> templ = <span class="string">[[
 #include &lt;lua.h&gt;
 #include &lt;lauxlib.h&gt;
 #include &lt;lualib.h&gt;

 &gt; for _,f in ipairs(mod) do
 static int l_$(f.name) (lua_State *L) {

 }
 &gt; end

 static const luaL_reg $(mod.name)[] = {
 &gt; for _,f in ipairs(mod) do
     {"$(f.name)",l_$(f.name)},
 &gt; end
     {NULL,NULL}
 };

 int luaopen_$(mod.name) {
    luaL_register (L, "$(mod.name)", $(mod.name));
     return 1;
 }
 ]]</span>

 <span class="global">print</span>(subst(templ,{
     _escape = <span class="string">'&gt;'</span>,
     <span class="global">ipairs</span> = <span class="global">ipairs</span>,
     mod = {
         name = <span class="string">'baggins'</span>;
         {name=<span class="string">'frodo'</span>},
         {name=<span class="string">'bilbo'</span>}
     }
 }))
</pre>


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

<h3>File-style I/O on Strings</h3>

<p><a href="../modules/pl.stringio.html#">pl.stringio</a>   provides just three functions; <a href="../modules/pl.stringio.html#open">stringio.open</a>  is passed a string, and returns a file-like object for reading. It supports a <code>read</code> method, which takes the same arguments as standard file objects:</p>

<pre>
 &gt; f = stringio.open <span class="string">'first line\n10 20 30\n'</span>
 &gt; = f:read()
 first line
 &gt; = f:read(<span class="string">'*n'</span>,<span class="string">'*n'</span>,<span class="string">'*n'</span>)
 <span class="number">10</span>    <span class="number">20</span>    <span class="number">30</span>
</pre>


<p><code>lines</code> and <code>seek</code> are also supported.</p>

<p><code>stringio.lines</code> is a useful short-cut for iterating over all the lines in a string.</p>

<p><a href="../modules/pl.stringio.html#create">stringio.create</a>  creates a writeable file-like object. You then use <code>write</code> to this stream, and finally extract the builded string using <code>value</code>.  This &lsquo;string builder&rsquo; pattern is useful for efficiently creating large strings.</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>