c# pdf viewer open source : Switch page order pdf application Library cloud html .net windows class World%20of%20Warcraft%20Programming%20(2nd%20Edition)8-part1882

CHA P T ER
3
Basic Functions and Control
Structures
Chapter2showedyouthebasicsoftheLua programminglanguageusingthe
print()
and
type()
functions,without fullyexplainingwhat afunction is.In
addition,basiccontrolstructures such as loops andconditionalshaven’tbeen
introducedyet.
The first part of this chapter explains the concept of functions and guides
you through creating several of your own. The second half introduces the
basiclooping andconditionalstatements.
Using Functions
Afunctionisaportionofaprogramthatcanbeusedtosimplifyrepeatedtasks
or perform complexcalculations. When a function is calledit may be passed
several arguments,thatis,data thatthefunction can useforthe duration ofits
execution.When a function completes,it can return any number ofvalues to
thecallingportionoftheprogram.
Creating a Function
The
function
keyword is used to create a new function, which can then be
storedin a variable or called directly. A basic function declaration looks like
this(typethisintoyourLuainterpreter):
> hello = function()
>> print(“Hello World!“)
>> end
39
Switch page order pdf - re-order PDF pages in C#.net, ASP.NET, MVC, Ajax, WinForms, WPF
Support Customizing Page Order of PDF Document in C# Project
pdf page order reverse; rearrange pdf pages in preview
Switch page order pdf - VB.NET PDF Page Move Library: re-order PDF pages in vb.net, ASP.NET, MVC, Ajax, WinForms, WPF
Sort PDF Document Pages Using VB.NET Demo Code
rearrange pages in pdf reader; how to reorder pdf pages in reader
40
Part I
Learning to Program
Thefunction constructor begins whereyou type
function()
and continues
tothe matching
end
keyword,withthecode betweenthesedelimitersmaking
up the body of the function. The Lua interpreter recognizes the new block
of code and indents the prompt to show you’re continuing the same section
of code (until you type the final
end
). In this case, a function is created that
takes no arguments (more on this in the next section) and prints the string
Hello World
before ending. The resulting function value is then assigned to
thevariable
hello
.Testthisfunction by runningthefollowing:
> hello()
Hello World!
Now,insteadoftyping
print(“Hello World“)
everytimeyouwanttoprint
that string, you can simply type
hello()
to call the new function. This is an
extremely simple example, but you use the full power of functions as you
movethrough the examplesin thischapter.
Local Functions
The function constructor returns a new Lua value, so it can be assigned to a
local variable the same as any othervalue. This can be useful when defining
functionsthatarecalledwithinyouraddons,butneednotbeexposedforother
addons to call. Local variables are difficult to explore in the Lua interpreter
because each lineofcodeis in its own scope,but you mayfindthe technique
ofusing local functionsuseful when working throughtherestofthisbook.
SYNTACTIC SUGAR
Lua provides a differentway todefinefunctionsthat is more conventionaland
may beeasierto read. Examinethe followingfunction definition:
functionhello()
print(“HelloWorld!“)
end
Whenthe Lua interpreter encounters thisdefinition, it is converted into the
definition usedintheprevioussection:
hello=function()
print(“HelloWorld!“)
end
That is tosay, the two definitions endup running the same code in the
interpreter. Functionsdefinedinthis manner canbemade localby adding the
keywordlocalbefore the functionconstructor, such as:
localfunctionhello()
print(“HelloWorld“)
end
(continued)
VB.NET PowerPoint: Sort and Reorder PowerPoint Slides by Using VB.
index = pageCount End If If i = pageCount - 1 Then ' Switch the first Add(index) Next ' Sort the PowerPoint slides using the correct order. PPT Page Extracting.
move pdf pages; pdf reverse page order online
DocImage SDK for .NET: Document Imaging Features
hi-fi diplay when zoomed Quick to switch mode of control Zoom, pan, or select document page with mouse saving and printing, like office document to PDF or TIFF
how to rearrange pages in a pdf reader; change page order in pdf online
Chapter 3
Basic Functionsand ControlStructures
41
SYNTACTIC SUGAR(continued)
When the localkeyword is used, itis convertedto roughly thefollowing
version:
localhello
hello=function()
print(“Hello World“)
end
Function Arguments and Returns
Whenafunctioniscalled,itcanbepassedanynumberofargumentstobeused
throughout the body of the function. In addition, a function may return any
numberofvalues when it completes.This allows forthe creation of dynamic
functions that can operate on values that are passedinto the function, rather
than some staticformulaorprocess.
Simple and repetitive tasks such as converting degrees Celsius to degrees
Fahrenheit can easily be made into functions that use arguments and return
values.
Converting Celsius toFahrenheit
The conversion formula given for temperature conversion is ‘‘Multiply the
temperature in degrees Celsius by 1.8 and add 32 to the result.’’ Instead of
performingthisconversionwitharithmeticeachtime,afunctioncanbewritten
that takes a number as an argument and returns the converted value as the
answer.TypethefollowingintoyourLua interpreter:
convert_c2f = function(celsius)
local converted = (celsius * 1.8) + 32
return converted
end
Here,afunctioniscreatedwith asingleargument,whichisnamed
celsius
.
Thefirstlineofthenewfunctioncalculatestheconvertedvalueandthesecond
linereturns it.Toseehowthis works,typethefollowing:
> print(convert_c2f(0))
32
> print(convert_c2f(-40))
-40
When the new function is called, the first argument passed to it (the
number
0
)is assigned to a local variable named
celsius
(corresponding to
the name given in the function). This allows you to define the formula for
conversionwithoutneedingtoknowthespecificnumberyouareconverting.
C# Image: Create C#.NET Windows Document Image Viewer | Online
is the option to "Add new page" or "delete page". OnFileAdded: Mainly in order to obtain the total number of value of selected drop-down list to switch pages.
reordering pages in pdf document; how to move pages in pdf
.NET Windows Forms Bar Code Installation and Creation Tutorial &
Choose Toolbox under View to display the Toolbox. Right click the Toolbox and select "choose items", and switch to the ".NET Framework Components";
how to reorder pages in a pdf document; how to rearrange pdf pages
42
Part I
Learning to Program
Empty Arguments
Trythefollowingin yourinterpreter:
> print(convert_c2f())
stdin:2: attempt to perform arithmetic on local 'celsius' (a nil value)
stack traceback:
stdin:2: in function 'convert_c2f'
stdin:1: in main chunk
[C]: ?
When no value is passed as an argument, the argument gets the value of
nil
.Thefirstlineofthe
convert_c2f
functiontriestomultiply
celsius
by
1.8
anderrorsoutbecause
nil
can’tbepartof an arithmeticexpression.Asimilar
errorwill occurifyoupassothernon-numbervaluesintothisfunction.
No ReturnValues
Not every function you encounter will have a return statement because not
all functions need to return anything. The
hello()
function defined earlier
in this chapter is one such example. In these cases any assignments or other
expressions involving a call to the function will evaluate to
nil
.Here’s an
example:
> function hello() print(“Hello World!“) end
> test = hello()
Hello World!
> print(type(test))
nil
Functions as Lua Values
Each function in Lua is just a plain Lua value of the type
function
.These
values can be compared (using
==
and
~=
),bound to variable names, passed
to functions, returned from functions, and used as keys in tables (tables are
exploredinChapter4).ALuavaluethatistreatedthiswayiscalledafirst-class
object, and a language that supports functions in this way is said to have
first-classfunctions.
Runthefollowingin yourinterpreter:
> hello = function() print(“Hello World!“) end
This creates a new function called
hello
.This value can now be compared
in the samewayyou’dcompare anyotherLuavalue.
> print(hello == hello)
true
> hello2 = hello
> print(hello2 == hello)
.NET Windows Forms PDF417 Bar Code Control & SDK
Choose Toolbox under View to display the Toolbox. Right click the Toolbox and select "choose items", and switch to the ".NET Framework Components";
how to move pages in pdf reader; how to move pages in pdf acrobat
Chapter 3
Basic Functionsand ControlStructures
43
true
> hello2()
Hello World!
> hello2 = function() print(“Hello World!“) end
> print(hello2 == hello)
false
In the final lines of the preceding example, a new function is created and
boundto
hello2
.Even though thenewfunctionhastheexactsamedefinition
andbody as
hello
,itisactually adistinctfunction.
Making Decisions with the if Statement
The
if
statement is the basis for decision making in Lua, and it supports
simple conditionals as well as more complex statements. The syntax of the
mostbasic
if
statementlooks likethis:
if <boolean expression> then
-- do something
end
Simple Conditionals
An
if
statement can be used to execute a block of code conditionally when
theBooleanexpression evaluatestotrue.Tobetterseethis,typethefollowing
intoyourinterpreter:
function conditional_test(num)
print(“You input: “ .. num)
if (num == 7) then
print(“You found the magic number!“)
end
end
This example function prints whatever number it gets passed, but if the
number 7 is passed, it will print an additional special message. Input this
function intoyourinterpreter,andthentestit withthefollowing:
> conditional_test(3)
You input: 3
> conditional_test(7)
You input: 7
You found the magic number!
> conditional_test(13)
You input: 13
44
Part I
Learning to Program
As with other arithmeticand Boolean expressions, theparentheses around
the conditional are not strictly necessary, but they can certainly make code
easiertoread.
Complex Expressions
InadditiontosimpleBooleanconditions,Luasupportsmorecomplexexpres-
sions solong as the expression evaluatesto aBoolean value.Thatallowsyou
to combine multiple conditions using the logical operators (
and
,
or
)into a
single complexcondition. Thefollowing areall validconditions (where
name
and
anonymous_flag
arevariables):
name
type(name) == “string“
(not anonymous_flag) and (type(name) == “string“)
Thefirstexamplesimplycheckstoseethatthevariable
name
isanythingother
than
nil
or
false
.Thesecondexamplecheckstoverifythatthevariable
name
is
astring,andthe final examplecheckstoseethat the variable
anonymous_flag
is either
false
or
nil
,andthe
name
variable isastring.
Extended Conditionals
Anextendedformofthe
if
statementallows youtochain multipleconditions
together,as well as provide a default for when no condition is matched. The
full syntaxforthe
if
statementis:
if <boolean expression> then
-- if part
elseif <boolean expression> then
-- elseif part
elseif <boolean expression> then
-- another elseif part
else
-- else part
end
Whentheinterpreterrunsthisexpression,itcheckseachconditioninorder,
stoppingatthefirstexpressionthatevaluatestotrueandrunningthatportion
ofthecode. If noneoftheexpressionsaretrue, the code in the
else
section is
run.Notevery
if
statementwill include
elseif
or
else
options,buttheyare
always availableifyouneedthem.
Usingthisformof
if
/
elseif
/
else
ensuresthatonlyoneactionintheentire
if
statement will be taken.If you were to write itusing a series ofsimple
if
statements,morethan onemay be called,asin thefollowingexample.
Chapter 3
Basic Functionsand ControlStructures
45
if <first condition> then
-- do something
end
if <second condition> then
-- do something
end
Bothtypesofconstructsareusefulbutyoushouldensure youareusingthe
correct one, so your program behaves correctly depending on whether you
needtotakeoneaction based on a condition,orevaluatemultiple conditions
independently.
Displaying a Personalized Greeting
Conditionals can be usedtoverify the arguments to a function. For example,
consider a function that takes a name (or
nil
)and prints out a personalized
greeting.Define this function inyourLua interpreter:
function greeting(name)
if (type(name) == “string“) then
print(“Hello “ .. name)
elseif (type(name) == “nil“) then
print(“Hello friend“)
else
error(“Invalid name was entered“)
end
end
The first condition checks to see if the
name
argument is a
string
, in
which caseit generates andprints a customgreeting. If the
name
argument is
nil
,meaning nothing was passed into the function, it will print the generic
string
Hello friend
.Finally, if neither of the previous conditions match, the
functiontriggersa customerrormessageusingthe
error()
function.Testthis
newfunctioninyourinterpreter:
> greeting(“Frank“)
Hello Frank
> greeting()
Hello friend
> greeting(13)
stdin:7: Invalid name was entered
stack traceback:
[C]: in function 'error'
stdin:7: in function 'greeting'
stdin:1: in main chunk
[C]: ?
46
Part I
Learning to Program
When the
error()
function is called, Lua provides the error message
suppliedalong with a stack traceback.In this case,youcan see that theerror
was triggeredfromthe
greeting()
function,which was calledfromthe main
chunk.
Thepreceding
greeting()
function couldhave been writtenwithoutusing
the
elseif
statement,by usingnested
if
statements,as follows:
function greeting(name)
if (type(name) == “string“) then
print(“Hello “ .. name)
else
if (type(name) == “nil“) then
print(“Hello friend“)
else
error(“Invalid name was entered“)
end
end
end
The nested style is useful in certain situations when you have multiple
conditions butalsoneedto havean
else
portion foreach of them. In general,
use whateverstyle you considerto be morereadableand appropriate for the
given situation.
Repeating Actions with the while Statement
Computersareoftenusedtorepeattasksorsimplifycomplexcalculationsthat
wouldotherwiserequiremanualrepetition.Luaprovidesthe
while
statement,
which will repeata block of code as long as a specified condition is met. The
while
statement’ssyntaxis:
while <boolean expression> do
-- body
end
The Boolean expression is evaluated on each and every repetition of the
loop,andtheloopwillcontinueas longastheconditionevaluatesto true.
Computing Factorials
Theprocessofcomputinganumber’sfactorialisagoodexampleofsomething
thatiseasilyautomated.Thefactorialofanumberx
iscomputedbymultiplying
all of the numbers from
1
to
x
together. Thus,
3
factorial is
1 * 2 * 3
.If a
function
factorial()
is defined, you can simply type
print(factorial(9))
Chapter 3
Basic Functionsand ControlStructures
47
insteadof
print(9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1)
.Definethis function
nowbytypingthefollowingdefinition into yourinterpreter:
function factorial(num)
local total = 1
while (num > 1) do
print(“total: “.. total .. “ num: “ .. num)
total = total * num
num = num - 1
end
return total
end
This function includes a
print()
statement that will show you what the
functiondoesoneachiterationoftheloop.Beforeusingthiscodeinanaddon,
remove that line from the function, or simply comment it out. For now, test
thisinyourLuainterpreter:
> print(factorial(5))
total: 1 num: 5
total: 5 num: 4
total: 20 num: 3
total: 60 num: 2
120
You can see each step of the loop and how the value is being calculated.
Using debug statements like this can be really handy when writingcode, but
youhavetoremembertoremovethembefore youreleasethe code.
NOTE
Theconditionofawhilestatementischeckedpriortorunningtheloop,
andagainoneachsubsequentrunoftheloop.Thismeansiftheconditionisnever
met,thebodyofthewhileloopis neverexecuted,andLuajustskipspastit.
Differences Between while and repeat
The
repeat/until
loop is a variant of the
while
loop that has the following
form:
repeat
-- body
until <boolean expression>
Theprimarydifferencebetweenthe
while/do
loopanda
repeat/until
loop
is thattheconditionofa
repeat
loopischeckedattheend ofthecomputation,
so the loop of the body is always executed at least once. In other words,
the condition in a
while
statement is checked in order to continue the loop,
48
Part I
Learning to Program
whereas the condition in a
repeat
loop is checked in order to exit the loop.
Here’s howyou’ddefinea newfactorial function using this construct:
function factorial2(num)
local total = 1
repeat
total = total * num
num = num - 1
until (num < 1)
return total
end
You can verifythe results ofthis function bytesting it with a fewdifferent
values:
> print(factorial2(1))
1
> print(factorial2(2))
2
> print(factorial2(3))
6
> print(factorial2(5))
120
If you happened to test these two functions with some unexpected value,
suchas
-3
,youshouldseea difference between theresults:
> print(factorial(-3))
1
> print(factorial2(-3))
-3
When running
factorial()
,the
num
variable is already less than
1
, so
the
while
body never runs; it simply returns the default value of
1
.When
factorial2()
is called,the body of the loophappens once,which causes the
differentreturn valueof
-3
.
Looping with the Numeric for Statement
Astheprecedingfactorialfunctiondemonstrated,manyloopsbeginatasimple
integervalueandtheneitherincrementordecrementtosomepredefinedlimit.
Inthecaseof
factorial(9)
,theloopstartsat
9
andcontinuesuntilitreaches
1
.
Rather than managing this sort of loop yourself, the
for
statement provides
an easywaytowritetheseloops:
for variablename = start_value, end_value, step_value do
-- body
end
Documents you may be interested
Documents you may be interested