关闭

关闭

关闭

封号提示

内容

首页 Programming in Lua, 2Nd Edition.pdf

Programming in Lua, 2Nd Edition.pdf

Programming in Lua, 2Nd Edition…

上传者: cvgmt 2010-09-17 评分 0 0 0 0 0 0 暂无简介 简介 举报

简介:本文档为《Programming in Lua, 2Nd Editionpdf》,可适用于高等教育领域,主题内容包含ROBERTOIERUSALIMSCHYProgramminginLuaLuaorgeditionndLastupdate:WedJan::UTCP符等。

ROBERTOIERUSALIMSCHYProgramminginLuaLuaorgeditionndLastupdate:WedJan::UTCProgramminginLuaPropertyofIanBloss<ianlinkcdgmailcom>PropertyofIanBloss<ianlinkcdgmailcom>ProgramminginLuaSecondEditionRobertoIerusalimschyPUCRio,BrazilLuaorgRiodeJaneiroPropertyofIanBloss<ianlinkcdgmailcom>ProgramminginLua,SecondEditionbyRobertoIerusalimschyISBNCopyrightc,byRobertoIerusalimschyAllrightsreservedTheauthorcanbecontactedatrobertoluaorgBookcoverandillustrationsbyDimaquinaLualogodesignbyAlexandreNakoTypesettingbytheauthorusingLATEXAlthoughtheauthorusedhisbesteffortspreparingthisbook,heassumesnoresponsibilityforerrorsoromissions,orforanydamagethatmayresultfromtheuseoftheinformationpresentedhereAllproductnamesmentionedinthisbookaretrademarksoftheirrespectiveownersCIP–BibliotecadoDepartamentodeInformatica,PUCRioIerusalimschy,RobertoIProgramminginLuaRobertoIerusalimschy–nded–RiodeJaneiro,xviii,p:cmIncludesindexISBNLua(Programminglanguage)ITitle–dcPropertyofIanBloss<ianlinkcdgmailcom>toIda,Noemi,andAnaLuciaPropertyofIanBloss<ianlinkcdgmailcom>PropertyofIanBloss<ianlinkcdgmailcom>ContentsPrefacexiiiITheLanguageGettingStartedChunksSomeLexicalConventionsGlobalVariablesTheStandAloneInterpreterTypesandValuesNilBooleansNumbersStringsTablesFunctionsUserdataandThreadsExpressionsArithmeticOperatorsRelationalOperatorsLogicalOperatorsConcatenationPrecedenceTableConstructorsviiPropertyofIanBloss<ianlinkcdgmailcom>viiiContentsStatementsAssignmentLocalVariablesandBlocksControlStructuresbreakandreturnFunctionsMultipleResultsVariableNumberofArgumentsNamedArgumentsMoreAboutFunctionsClosuresNonGlobalFunctionsProperTailCallsIteratorsandtheGenericforIteratorsandClosuresTheSemanticsoftheGenericforStatelessIteratorsIteratorswithComplexStateTrueIteratorsCompilation,Execution,andErrorsCompilationCCodeErrorsErrorHandlingandExceptionsErrorMessagesandTracebacksCoroutinesCoroutineBasicsPipesandFiltersCoroutinesasIteratorsNonPreemptiveMultithreadingCompleteExamplesDataDescriptionMarkovChainAlgorithmIITablesandObjectsDataStructuresArraysPropertyofIanBloss<ianlinkcdgmailcom>ixMatricesandMultiDimensionalArraysLinkedListsQueuesandDoubleQueuesSetsandBagsStringBuffersGraphsDataFilesandPersistenceDataFilesSerializationMetatablesandMetamethodsArithmeticMetamethodsRelationalMetamethodsLibraryDefinedMetamethodsTableAccessMetamethodsTheEnvironmentGlobalVariableswithDynamicNamesGlobalVariableDeclarationsNonGlobalEnvironmentsModulesandPackagesTherequireFunctionTheBasicApproachforWritingModulesUsingEnvironmentsThemoduleFunctionSubmodulesandPackagesObjectOrientedProgrammingClassesInheritanceMultipleInheritancePrivacyTheSingleMethodApproachWeakTablesMemoizeFunctionsObjectAttributesRevisitingTableswithDefaultValuesIIITheStandardLibrariesTheMathematicalLibraryPropertyofIanBloss<ianlinkcdgmailcom>xContentsTheTableLibraryInsertandRemoveSortConcatenationTheStringLibraryBasicStringFunctionsPatternMatchingFunctionsPatternsCapturesReplacementsTricksoftheTradeTheIOLibraryTheSimpleIOModelTheCompleteIOModelOtherOperationsonFilesTheOperatingSystemLibraryDateandTimeOtherSystemCallsTheDebugLibraryIntrospectiveFacilitiesHooksProfilesIVTheCAPIAnOverviewoftheCAPIAFirstExampleTheStackErrorHandlingwiththeCAPIExtendingYourApplicationTheBasicsTableManipulationCallingLuaFunctionsAGenericCallFunctionCallingCfromLuaCFunctionsCModulesPropertyofIanBloss<ianlinkcdgmailcom>xiTechniquesforWritingCFunctionsArrayManipulationStringManipulationStoringStateinCFunctionsUserDefinedTypesinCUserdataMetatablesObjectOrientedAccessArrayAccessLightUserdataManagingResourcesADirectoryIteratorAnXMLParserThreadsandStatesMultipleThreadsLuaStatesMemoryManagementTheAllocationFunctionTheGarbageCollectorIndexPropertyofIanBloss<ianlinkcdgmailcom>PropertyofIanBloss<ianlinkcdgmailcom>PrefaceWhenWaldemar,Luiz,andIstartedthedevelopmentofLua,backin,wecouldhardlyimaginethatitwouldspreadasitdidStartedasaninhouselanguagefortwospecificprojects,currentlyLuaiswidelyusedinallareasthatcanbenefitfromasimple,extensible,portable,andefficientscriptinglanguage,suchasembeddedsystems,mobiledevices,webservers,and,ofcourse,gamesWedesignedLua,fromthebeginning,tobeintegratedwithsoftwarewritteninCandotherconventionallanguagesThisintegrationbringsmanybenefitsLuaisatinyandsimplelanguage,partlybecauseitdoesnottrytodowhatCisalreadygoodfor,suchassheerperformance,lowleveloperations,andinterfacewiththirdpartysoftwareLuareliesonCforthesetasksWhatLuadoesofferiswhatCisnotgoodfor:agooddistancefromthehardware,dynamicstructures,noredundancies,easeoftestinganddebuggingForthis,Luahasasafeenvironment,automaticmemorymanagement,andgoodfacilitiesforhandlingstringsandotherkindsofdatawithdynamicsizeAgreatpartofthepowerofLuacomesfromitslibrariesThisisnotbychanceAfterall,oneofthemainstrengthsofLuaisitsextensibilityManyfeaturescontributetothisstrengthDynamictypingallowsagreatdegreeofpolymorphismAutomaticmemorymanagementsimplifiesinterfaces,becausethereisnoneedtodecidewhoisresponsibleforallocatinganddeallocatingmemory,orhowtohandleoverflowsHigherorderfunctionsandanonymousfunctionsallowahighdegreeofparameterization,makingfunctionsmoreversatileMorethananextensiblelanguage,LuaisalsoagluelanguageLuasupportsacomponentbasedapproachtosoftwaredevelopment,wherewecreateanapplicationbygluingtogetherexistinghighlevelcomponentsThesecomponentsarewritteninacompiled,staticallytypedlanguage,suchasCorCLuaisthegluethatweusetocomposeandconnectthesecomponentsUsually,thecomponents(orobjects)representmoreconcrete,lowlevelconcepts(suchaswidgetsanddatastructures)thatarenotsubjecttomanychangesduringprogramdevelopment,andthattakethebulkoftheCPUtimeofthefinalprogramLuagivesthefinalshapeoftheapplication,whichwillprobablychangealotduringthelifecycleoftheproductHowever,unlikeothergluetechnologies,LuaisafullfledgedlanguageaswellTherefore,wecanuseLuanotonlytoxiiiPropertyofIanBloss<ianlinkcdgmailcom>xivPrefacegluecomponents,butalsotoadaptandreshapethem,andtocreatewholenewcomponentsOfcourse,LuaisnottheonlyscriptinglanguagearoundThereareotherlanguagesthatyoucanuseformoreorlessthesamepurposesButLuaoffersasetoffeaturesthatmakesityourbestchoiceformanytasksandgivesitauniqueprofile:Extensibility:Lua’sextensibilityissoremarkablethatmanypeopleregardLuanotasalanguage,butasakitforbuildingdomainspecificlanguagesLuahasbeendesignedfromscratchtobeextended,boththroughLuacodeandthroughexternalCcodeAsaproofofconcept,LuaimplementsmostofitsownbasicfunctionalitythroughexternallibrariesItisreallyeasytointerfaceLuawithCC,andLuahasbeenusedintegratedwithseveralotherlanguagesaswell,suchasFortran,Java,Smalltalk,Ada,C#,andevenwithotherscriptinglanguages,suchasPerlandRubySimplicity:LuaisasimpleandsmalllanguageIthasfew(butpowerful)conceptsThissimplicitymakesLuaeasytolearnandcontributestoitssmallsizeItscompletedistribution(sourcecode,manual,plusbinariesforsomeplatforms)fitscomfortablyinafloppydiskEfficiency:LuahasaquiteefficientimplementationIndependentbenchmarksshowLuaasoneofthefastestlanguagesintherealmofscripting(interpreted)languagesPortability:Whenwetalkaboutportability,wearenottalkingaboutrunningLuabothonWindowsandonUnixplatformsWearetalkingaboutrunningLuaonallplatformswehaveeverheardabout:PlayStation,XBox,MacOSandOSX,BeOS,QUALCOMMBrew,MSDOS,IBMmainframes,RISCOS,SymbianOS,PalmOS,ARMprocessors,Rabbitprocessors,plusofcourseallflavorsofUnixandWindowsThesourcecodeforeachoftheseplatformsisvirtuallythesameLuadoesnotuseconditionalcompilationtoadaptitscodetodifferentmachinesinstead,itstickstothestandardANSI(ISO)CThisway,youdonotusuallyneedtoadaptittoanewenvironment:ifyouhaveanANSICcompiler,youjusthavetocompileLua,outoftheboxAudienceLuauserstypicallyfallintothreebroadgroups:thosethatuseLuaalreadyembeddedinanapplicationprogram,thosethatuseLuastandalone,andthosethatuseLuaandCtogetherManypeopleuseLuaembeddedinanapplicationprogram,suchasCGILua(forbuildingdynamicWebpages)oragameTheseapplicationsusetheLua–CAPItoregisternewfunctions,tocreatenewtypes,andtochangethebehaviorofsomelanguageoperations,configuringLuafortheirspecificdomainsFrequently,theusersofsuchapplicationsdonotevenknowthatLuaisanindependentlanguageadaptedforaparticulardomainforinstance,CGILuausersPropertyofIanBloss<ianlinkcdgmailcom>xvtendtothinkofLuaasalanguagespecificallydesignedfortheWebplayersofaspecificgamemayregardLuaasalanguageexclusivetothatgameLuaisusefulalsoasastandalonelanguage,notonlyfortextprocessingandoneshotlittleprograms,butincreasinglyformediumtolargeprojects,tooForsuchuses,themainfunctionalityofLuacomesfromlibrariesThestandardlibrariesofferpatternmatchingandotherfunctionsforstringhandling(WemayregardthestandalonelanguageastheembeddingofLuaintothedomainofstringandtextfilemanipulation)AsLuaimprovesitssupportforlibraries,therehasbeenaproliferationofexternalpackagesTheKeplerproject(http:wwwkeplerprojectorg),forinstance,isaWebdevelopmentplatformforLuathatofferspackagesforpagegeneration,databaseaccess,LDAP,XML,andSOAPTheLuaForgesite(http:wwwluaforgenet)offersafocalpointformanyLuapackagesFinally,therearethoseprogrammersthatworkontheothersideofthebench,writingapplicationsthatuseLuaasaClibraryThosepeoplewillprogrammoreinCthaninLua,althoughtheyneedagoodunderstandingofLuatocreateinterfacesthataresimple,easytouse,andwellintegratedwiththelanguageThisbookhasmuchtooffertoallthesepeopleThefirstpartcoversthelanguageitself,showinghowwecanexploreallitspotentialWefocusondifferentlanguageconstructsandusenumerousexamplestoshowhowtousethemforpracticaltasksSomechaptersinthispartcoverbasicconcepts,suchascontrolstructures,buttherearealsoadvancedtopics,suchasiteratorsandcoroutinesThesecondpartisentirelydevotedtotables,thesoledatastructureinLuaItschaptersdiscussdatastructures,persistence,packages,andobjectorientedprogrammingTherewewillunveiltherealpowerofthelanguageThethirdpartpresentsthestandardlibrariesThispartisparticularlyusefulforthosethatuseLuaasastandalonelanguage,althoughmanyotherapplicationsalsoincorporateallorpartofthestandardlibrariesThispartdevotesonechaptertoeachstandardlibrary:themathematicallibrary,thetablelibrary,thestringlibrary,theIOlibrary,theoperatingsystemlibrary,andthedebuglibraryFinally,thelastpartofthebookcoverstheAPIbetweenLuaandC,forthosethatuseCtogetthefullpowerofLuaThispartnecessarilyhasaflavorquitedifferentfromtherestofthebookTherewewillbeprogramminginC,notinLuatherefore,wewillbewearingadifferenthatForsomereaders,thediscussionoftheCAPImaybeofmarginalinterestforothers,itmaybethemostrelevantpartofthisbookAbouttheSecondEditionThisbookisanupdatedandexpandedversionofthefirsteditionofProgramminginLua(alsoknownasthePiLbook)Althoughthebookstructureisvirtuallythesame,thisneweditionhassubstantialnewmaterialPropertyofIanBloss<ianlinkcdgmailcom>xviPrefaceFirst,IhaveupdatedthewholebooktoLuaOfparticularrelevanceisthechapteraboutmodulesandpackages,whichwasmostlyrewrittenIalsorewroteseveralexamplestoshowhowtobenefitfromthenewfeaturesofferedbyLuaNevertheless,IclearlymarkedfeaturesabsentfromLua,soyoucanusethebookforthatversiontooSecond,thereareseveralnewexamplesTheseexamplescovergraphrepresentation,tabexpansionandcompression,animplementationfortuples,andmoreThird,therearetwocompletenewchaptersOneisabouthowtousemultiplestatesandmultiplethreadsfromCitincludesaniceexampleofhowtoimplementamultiprocessfacilityforLuaTheotherisaboutmemorymanagementandhowtointeractwithmemoryallocationandgarbagecollectionAfterthereleaseofthefirsteditionofProgramminginLua,severalpublisherscontactedusshowinginterestinasecondeditionIntheend,however,wedecidedtoselfpublishthissecondedition,aswedidwiththefirstoneDespitethelimitedmarketing,thisavenuebringsseveralbenefits:wehavetotalcontroloverthebookcontents,wehavefreedomtochoosewhentoreleaseanotheredition,wecanensurethatthebookdoesnotgooutofprint,andwekeepthefullrightstoofferthebookinotherformsOtherResourcesThereferencemanualisamustforanyonewhowantstoreallylearnalanguageThisbookdoesnotreplacetheLuareferencemanualQuitetheopposite,theycomplementeachotherThemanualonlydescribesLuaItshowsneitherexamplesnorarationalefortheconstructsofthelanguageOntheotherhand,itdescribesthewholelanguagethisbookskipsoverseldomuseddarkcornersofLuaMoreover,themanualistheauthoritativedocumentaboutLuaWhereverthisbookdisagreeswiththemanual,trustthemanualTogetthemanualandmoreinformationaboutLua,visittheLuasiteathttp:wwwluaorgYoucanalsofindusefulinformationattheLuauserssite,keptbythecommunityofusersathttp:luausersorgAmongotherresources,itoffersatutorial,alistofthirdpartypackagesanddocumentation,andanarchiveoftheofficialLuamailinglistYoushouldcheckalsothebook’swebpage:http:wwwinfpucriobr~robertopilThereyoucanfindupdatederrata,codeforsomeoftheexamplespresentedinthebook,andsomeextramaterialThisbookdescribesLua,althoughmostofitscontentsalsoapplytoLuaThefewdifferencesbetweenLuaandLuaareclearlymarkedinthetextIfyouareusingamorerecentversion,checkthecorrespondingmanualforoccasionaldifferencesbetweenversionsIfyouareusingaversionolderthan,thisisagoodtimetoupgradePropertyofIanBloss<ianlinkcdgmailcom>xviiAFewTypographicalConventionsThebookencloses“literalstrings”betweendoublequotesandsinglecharacters,like‘a’,betweensinglequotesStringsthatareusedaspatternsarealsoenclosedbetweensinglequotes,like‘w*’ThebookusesatypewriterfontbothforlittlechunksofcodeandforidentifiersLargerchunksofcodeareshownindisplaystyle:program"HelloWorld"print("HelloWorld")>HelloWorldThenotation>showstheoutputofastatementor,occasionally,theresultofanexpression:print()>>Becauseadoublehyphen()startsacommentinLua,thereisnoproblemifyouincludetheseannotationsinyourprogramsFinally,thebookusesthenotation<>toindicatethatsomethingisequivalenttosomethingelse:this<>thatThatis,itmakesnodifferencetoLuawhetheryouwritethisorthatAcknowledgmentsThisbookwouldbeimpossiblewithoutthehelpofseveralfriendsandinstitutionsAsalways,LuizHenriquedeFigueiredoandWaldemarCeles,Luacodevelopers,offeredallkindsofhelpGavinWraith,AndreCarregal,AskoKauppi,BrettKapilik,JohnDRamsdell,andEdwinMoragasrevieweddraftsofthisbookandprovidedinvaluablesuggestionsLightningSource,IncprovedareliableandefficientoptionforprintinganddistributingthebookWithoutthem,theoptionofselfpublishingthebookwouldprobablynotbeanoptionAntonioPedro,fromDimaquina,patientlyenduredmyshiftingopinionsandproducedtherightcoverdesignNormanRamseykindlyprovidedusefulinsightsaboutthebestwaytopublishthisbookIalsowouldliketothankPUCRioandCNPqfortheircontinuoussupporttomyworkFinally,ImustexpressmydeepgratitudetoNoemiRodriguez,forilluminingmylifePropertyofIanBloss<ianlinkcdgmailcom>PropertyofIanBloss<ianlinkcdgmailcom>PartITheLanguagePropertyofIanBloss<ianlinkcdgmailcom>PropertyofIanBloss<ianlinkcdgmailcom>GettingStartedTokeepwiththetradition,ourfirstprograminLuajustprints“HelloWorld”:print("HelloWorld")IfyouareusingthestandaloneLuainterpreter,allyouhavetodotorunyourfirstprogramistocalltheinterpreterusuallynamedluawiththenameofthetextfilethatcontainsyourprogramIfyouwritetheaboveprograminafilehellolua,thefollowingcommandshouldrunit:luahelloluaAsamorecomplexexample,thenextprogramdefinesafunctiontocomputethefactorialofagivennumber,thenaskstheuserforanumberandprintsitsfactorial:definesafactorialfunctionfunctionfact(n)ifn==thenreturnelsereturnn*fact(n)endendprint("enteranumber:")a=ioread("*number")readanumberprint(fact(a))PropertyofIanBloss<ianlinkcdgmailcom>ChapterGettingStartedIfyouareusingLuaembeddedinanapplication,suchasCGILuaorIUPLua,youmayneedtorefertotheapplicationmanual(ortoa“localguru”)tolearnhowtorunyourprogramsNevertheless,LuaisstillthesamelanguagemostthingsthatwewillseeherearevalidregardlessofhowyouareusingLuaIrecommendthatyoustartyourstudy

职业精品

用户评论

0/200
    暂无评论

精彩专题

上传我的资料

热门资料

资料评价:

/49
仅支持在线阅读

意见
反馈

返回
顶部