1 -- QuickLuaTour.lua
2 --
3 -- A quick tour of the Lua Scripting Language.
4 --
5 -- Created: May 21, 2008,
6 -- Updated: Sept 4th, 2008 Fix typos, minor changes, better formatting.
7 -- Author: AGR Wilson
8 -- Some more updates and fixes by Dirk Feytons.
9 --
10 -- To add later? - serialize table, self-executing code, closures, co-routines.
11 --
12
13 local codeSamples ={
14 [==[
15 -- First Program.
16 -- Classic hello program.
17
18 print("hello")
19
20 ]==],
21
22 [==[
23 -- Comments.
24 -- Single line comments in Lua start with double hyphen.
25
26 --[[ Multiple line comments start
27 with double hyphen and two square brackets.
28 and end with two square brackets. ]]
29
30 -- And of course this example produces no
31 -- output, since it's all comments!
32
33 ]==],
34
35 [==[
36 -- Variables.
37 -- Variables hold values which have types, variables don't have types.
38
39 a=1
40 b="abc"
41 c={}
42 d=print
43
44 print(type(a))
45 print(type(b))
46 print(type(c))
47 print(type(d))
48 ]==],
49
50 [==[
51 -- Variable names.
52 -- Variable names consist of letters, digits and underscores.
53 -- They cannot start with a digit.
54
55 one_two_3 = 123 -- is valid varable name
56
57 -- 1_two_3 is not a valid variable name.
58
59 ]==],
60
61 [==[
62 -- More Variable names.
63 -- The underscore is typically used to start special values
64 -- like _VERSION in Lua.
65
66 print(_VERSION)
67
68 -- So don't use variables that start with _,
69 -- but a single underscore _ is often used as a
70 -- dummy variable.
71
72 ]==],
73 [==[
74 -- Case Sensitive.
75 -- Lua is case sensitive so all variable names & keywords
76 -- must be in correct case.
77
78 ab=1
79 Ab=2
80 AB=3
81 print(ab,Ab,AB)
82
83 ]==],
84 [==[
85 -- Keywords.
86 -- Lua reserved words are: and, break, do, else, elseif,
87 -- end, false, for, function, if, in, local, nil, not, or,
88 -- repeat, return, then, true, until, while.
89
90 -- Keywords cannot be used for variable names,
91 -- 'and' is a keyword, but AND is not, so it is a legal variable name.
92 AND=3
93 print(AND)
94
95 ]==],
96
97 [==[
98 -- Strings.
99
100 a="single 'quoted' string and double \"quoted\" string inside"
101 b='single \'quoted\' string and double "quoted" string inside'
102 c= [[ multiple line
103 with 'single'
104 and "double" quoted strings inside.]]
105
106 print(a)
107 print(b)
108 print(c)
109 ]==],
110
111 [==[
112 -- Assignments.
113 -- Multiple assignments are valid.
114 -- var1,var2=var3,var4
115
116 a,b,c,d,e = 1, 2, "three", "four", 5
117
118 print(a,b,c,d,e)
119
120 ]==],
121 [==[
122 -- More Assignments.
123 -- Multiple assignments allows one line to swap two variables.
124
125 print(a,b)
126 a,b=b,a
127 print(a,b)
128
129 ]==],
130 [==[
131 -- Numbers.
132 -- Multiple assignment showing different number formats.
133 -- Two dots (..) are used to concatenate strings (or a
134 -- string and a number).
135
136 a,b,c,d,e = 1, 1.123, 1E9, -123, .0008
137 print("a="..a, "b="..b, "c="..c, "d="..d, "e="..e)
138
139 ]==],
140 [==[
141 -- More Output.
142 -- More writing output.
143
144 print "Hello from Lua!"
145 print("Hello from Lua!")
146
147 ]==],
148 [==[
149 -- More Output.
150 -- io.write writes to stdout but without new line.
151
152 io.write("Hello from Lua!")
153 io.write("Hello from Lua!")
154
155 -- Use an empty print to write a single new line.
156 print()
157
158 ]==],
159
160 [==[
161 -- Tables.
162 -- Simple table creation.
163
164 a={} -- {} creates an empty table
165 b={1,2,3} -- creates a table containing numbers 1,2,3
166 c={"a","b","c"} -- creates a table containing strings a,b,c
167 print(a,b,c) -- tables don't print directly, we'll get back to this!!
168 ]==],
169
170 [==[
171 -- More Tables.
172 -- Associate index style.
173
174 address={} -- empty address
175 address.Street="Wyman Street"
176 address.StreetNumber=360
177 address.AptNumber="2a"
178 address.City="Watertown"
179 address.State="Vermont"
180 address.Country="USA"
181
182 print(address.StreetNumber, address["AptNumber"])
183
184 ]==],
185
186 [==[
187 -- if statement.
188 -- Simple if.
189
190 a=1
191 if a==1 then
192 print ("a is one")
193 end
194 ]==],
195
196 [==[
197 -- if else statement.
198
199 b="happy"
200 if b=="sad" then
201 print("b is sad")
202 else
203 print("b is not sad")
204 end
205 ]==],
206
207 [==[
208 -- if elseif else statement
209
210 c=3
211 if c==1 then
212 print("c is 1")
213 elseif c==2 then
214 print("c is 2")
215 else
216 print("c isn't 1 or 2, c is "..tostring(c))
217 end
218 ]==],
219
220 [==[
221 -- Conditional assignment.
222 -- value = test and x or y
223
224 a=1
225 b=(a==1) and "one" or "not one"
226 print(b)
227
228 -- is equivalent to
229 a=1
230 if a==1 then
231 b = "one"
232 else
233 b = "not one"
234 end
235 print(b)
236 ]==],
237
238 [==[
239 -- while statement.
240
241 a=1
242 while a~=5 do -- Lua uses ~= to mean not equal
243 a=a+1
244 io.write(a.." ")
245 end
246 ]==],
247
248 [==[
249 -- repeat until statement.
250
251 a=0
252 repeat
253 a=a+1
254 print(a)
255 until a==5
256 ]==],
257
258 [==[
259 -- for statement.
260 -- Numeric iteration form.
261
262 -- Count from 1 to 4 by 1.
263 for a=1,4 do io.write(a) end
264
265 print()
266
267 -- Count from 1 to 6 by 3.
268 for a=1,6,3 do io.write(a) end
269 ]==],
270
271 [==[
272 -- More for statement.
273 -- Sequential iteration form.
274
275 for key,value in pairs({1,2,3,4}) do print(key, value) end
276 ]==],
277
278 [==[
279 -- Printing tables.
280 -- Simple way to print tables.
281
282 a={1,2,3,4,"five","elephant", "mouse"}
283
284 for i,v in pairs(a) do print(i,v) end
285 ]==],
286
287 [==[
288 -- break statement.
289 -- break is used to exit a loop.
290
291 a=0
292 while true do
293 a=a+1
294 if a==10 then
295 break
296 end
297 end
298
299 print(a)
300 ]==],
301
302 [==[
303 -- Functions.
304
305 -- Define a function without parameters or return value.
306 function myFirstLuaFunction()
307 print("My first lua function was called")
308 end
309
310 -- Call myFirstLuaFunction.
311 myFirstLuaFunction()
312 ]==],
313
314 [==[
315 -- More functions.
316
317 -- Define a function with a return value.
318 function mySecondLuaFunction()
319 return "string from my second function"
320 end
321
322 -- Call function returning a value.
323 a=mySecondLuaFunction("string")
324 print(a)
325 ]==],
326
327 [==[
328 -- More functions.
329
330 -- Define function with multiple parameters and multiple return values.
331 function myFirstLuaFunctionWithMultipleReturnValues(a,b,c)
332 return a,b,c,"My first lua function with multiple return values", 1, true
333 end
334
335 a,b,c,d,e,f = myFirstLuaFunctionWithMultipleReturnValues(1,2,"three")
336 print(a,b,c,d,e,f)
337 ]==],
338
339 [==[
340 -- Variable scoping and functions.
341 -- All variables are global in scope by default.
342
343 b="global"
344
345 -- To make local variables you must put the keyword 'local' in front.
346 function myfunc()
347 local b=" local variable"
348 a="global variable"
349 print(a,b)
350 end
351
352 myfunc()
353 print(a,b)
354 ]==],
355
356 [==[
357 -- Formatted printing.
358 -- An implementation of printf.
359
360 function printf(fmt, ...)
361 io.write(string.format(fmt, ...))
362 end
363
364 printf("Hello %s from %s on %s\n",
365 os.getenv"USER" or "there", _VERSION, os.date())
366 ]==],
367
368 [==[
369 --[[
370
371 Standard Libraries
372
373 Lua has standard built-in libraries for common operations in
374 math, string, table, input/output & operating system facilities.
375
376 External Libraries
377
378 Numerous other libraries have been created: sockets, XML, profiling,
379 logging, unittests, GUI toolkits, web frameworks, and many more.
380
381 ]]
382
383 ]==],
384
385 [==[
386 -- Standard Libraries - math.
387
388 -- Math functions:
389 -- math.abs, math.acos, math.asin, math.atan, math.atan2,
390 -- math.ceil, math.cos, math.cosh, math.deg, math.exp, math.floor,
391 -- math.fmod, math.frexp, math.huge, math.ldexp, math.log, math.log10,
392 -- math.max, math.min, math.modf, math.pi, math.pow, math.rad,
393 -- math.random, math.randomseed, math.sin, math.sinh, math.sqrt,
394 -- math.tan, math.tanh
395
396 print(math.sqrt(9), math.pi)
397 ]==],
398
399 [==[
400 -- Standard Libraries - string.
401
402 -- String functions:
403 -- string.byte, string.char, string.dump, string.find, string.format,
404 -- string.gfind, string.gsub, string.len, string.lower, string.match,
405 -- string.rep, string.reverse, string.sub, string.upper
406
407 print(string.upper("lower"),string.rep("a",5),string.find("abcde", "cd"))
408 ]==],
409
410 [==[
411 -- Standard Libraries - table.
412
413 -- Table functions:
414 -- table.concat, table.insert, table.maxn, table.remove, table.sort
415
416 a={2}
417 table.insert(a,3);
418 table.insert(a,4);
419 table.sort(a,function(v1,v2) return v1 > v2 end)
420 for i,v in ipairs(a) do print(i,v) end
421 ]==],
422
423 [==[
424 -- Standard Libraries - input/output.
425
426 -- IO functions:
427 -- io.close , io.flush, io.input, io.lines, io.open, io.output, io.popen,
428 -- io.read, io.stderr, io.stdin, io.stdout, io.tmpfile, io.type, io.write,
429 -- file:close, file:flush, file:lines ,file:read,
430 -- file:seek, file:setvbuf, file:write
431
432 print(io.open("file doesn't exist", "r"))
433 ]==],
434
435 [==[
436 -- Standard Libraries - operating system facilities.
437
438 -- OS functions:
439 -- os.clock, os.date, os.difftime, os.execute, os.exit, os.getenv,
440 -- os.remove, os.rename, os.setlocale, os.time, os.tmpname
441
442 print(os.date())
443 ]==],
444
445 [==[
446 -- External Libraries.
447 -- Lua has support for external modules using the 'require' function
448 -- INFO: A dialog will popup but it could get hidden behind the console.
449
450 require( "iuplua" )
451 ml = iup.multiline
452 {
453 expand="YES",
454 value="Quit this multiline edit app to continue Tutorial!",
455 border="YES"
456 }
457 dlg = iup.dialog{ml; title="IupMultiline", size="QUARTERxQUARTER",}
458 dlg:show()
459 print("Exit GUI app to continue!")
460 iup.MainLoop()
461 ]==],
462
463 [==[
464 --[[
465
466 To learn more about Lua scripting see
467
468 Lua Tutorials: http://lua-users.org/wiki/TutorialDirectory
469
470 "Programming in Lua" Book: http://www.inf.puc-rio.br/~roberto/pil2/
471
472 Lua 5.1 Reference Manual:
473 Start/Programs/Lua/Documentation/Lua 5.1 Reference Manual
474
475 Examples: Start/Programs/Lua/Examples
476 ]]
477
478 ]==],
479
480
481 }
482
483 -- for every code sample do
484 for i =1, #codeSamples do
485
486 -- clear screen
487 if os.getenv("OS")=="Windows_NT" then
488 os.execute("cls")
489 end
490
491 -- print code sample to console
492 io.write("\n-- Example "..i.." ")
493
494 print(codeSamples[i])
495
496 print ("\n-------- Output ------\n")
497
498 -- execute code sample
499 -- used protected call to load & execute codeSamples[i] as chunk of code
500 local ok, err = pcall(loadstring(codeSamples[i]))
501 if not ok then
502 print("failed to load & run sample code")
503 print(err)
504 end
505
506 io.write("\nPress 'Enter' key for next example")
507 io.read()
508
509 end -- for loop
510
511
512 print("\nYour Quick Lua Tour is complete!")