ebook img

Programming in Lua PDF

343 Pages·2013·0.921 MB·english
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview Programming in Lua

Programming in Lua Third Edition Roberto Ierusalimschy PUC-Rio, Brazil Lua.org Rio de Janeiro Programming in Lua, Third Edition byRobertoIerusalimschy ISBN978-85-903798-5-0 Copyright(cid:13)c 2013,2003byRobertoIerusalimschy. Allrightsreserved. [email protected]. CIP–BibliotecadoDepartamentodeInformática,PUC-Rio Ierusalimschy,Roberto I22 ProgramminginLua/RobertoIerusalimschy. –3thed. –RiodeJaneiro,2013. xviii,348p. : 25cm. Includesindex. ISBN978-85-903798-5-0 1. Lua(Programminglanguage). I.Title. 005.133–dc20 Feisty Duck Digital Book Distribution www.feistyduck.com Contents Preface xiii I The Language 1 1 GettingStarted 3 1.1 Chunks 4 1.2 SomeLexicalConventions 5 1.3 GlobalVariables 6 1.4 TheStand-AloneInterpreter 6 Exercises 8 2 TypesandValues 9 2.1 Nil 10 2.2 Booleans 10 2.3 Numbers 10 2.4 Strings 11 2.5 Tables 15 2.6 Functions 18 2.7 UserdataandThreads 18 Exercises 18 3 Expressions 21 3.1 ArithmeticOperators 21 3.2 RelationalOperators 22 3.3 LogicalOperators 23 3.4 Concatenation 23 3.5 TheLengthOperator 24 3.6 Precedence 25 3.7 TableConstructors 26 Exercises 28 4 Statements 29 4.1 Assignment 29 4.2 LocalVariablesandBlocks 30 4.3 ControlStructures 32 4.4 break,return,andgoto 36 Exercises 38 5 Functions 41 5.1 MultipleResults 42 5.2 VariadicFunctions 46 5.3 NamedArguments 48 Exercises 49 6 MoreaboutFunctions 51 6.1 Closures 53 6.2 Non-GlobalFunctions 56 6.3 ProperTailCalls 58 Exercises 59 7 IteratorsandtheGenericfor 61 7.1 IteratorsandClosures 61 7.2 TheSemanticsoftheGenericfor 63 7.3 StatelessIterators 64 7.4 IteratorswithComplexState 66 7.5 TrueIterators 67 Exercises 68 8 Compilation,Execution,andErrors 71 8.1 Compilation 71 8.2 PrecompiledCode 75 8.3 CCode 76 8.4 Errors 77 8.5 ErrorHandlingandExceptions 79 8.6 ErrorMessagesandTracebacks 79 Exercises 81 9 Coroutines 83 9.1 CoroutineBasics 83 9.2 PipesandFilters 86 9.3 CoroutinesasIterators 89 9.4 Non-PreemptiveMultithreading 91 Exercises 95 10 CompleteExamples 97 10.1 TheEight-QueenPuzzle 97 10.2 MostFrequentWords 99 10.3 MarkovChainAlgorithm 101 Exercises 102 II Tables and Objects 105 11 DataStructures 107 11.1 Arrays 107 11.2 MatricesandMulti-DimensionalArrays 108 11.3 LinkedLists 110 11.4 QueuesandDoubleQueues 110 11.5 SetsandBags 111 11.6 StringBuffers 113 11.7 Graphs 114 Exercises 116 12 DataFilesandPersistence 117 12.1 DataFiles 117 12.2 Serialization 119 Exercises 125 13 MetatablesandMetamethods 127 13.1 ArithmeticMetamethods 128 13.2 RelationalMetamethods 131 13.3 Library-DefinedMetamethods 132 13.4 Table-AccessMetamethods 133 Exercises 138 14 TheEnvironment 139 14.1 GlobalVariableswithDynamicNames 139 14.2 Global-VariableDeclarations 141 14.3 Non-GlobalEnvironments 142 14.4 Using_ENV 144 14.5 _ENVandload 147 Exercises 148 15 ModulesandPackages 151 15.1 TherequireFunction 153 15.2 TheBasicApproachforWritingModulesinLua 156 15.3 UsingEnvironments 158 15.4 SubmodulesandPackages 159 Exercises 161 16 Object-OrientedProgramming 163 16.1 Classes 165 16.2 Inheritance 166 16.3 MultipleInheritance 168 16.4 Privacy 170 16.5 TheSingle-MethodApproach 172 Exercises 173 17 WeakTablesandFinalizers 175 17.1 WeakTables 175 17.2 MemoizeFunctions 177 17.3 ObjectAttributes 179 17.4 RevisitingTableswithDefaultValues 179 17.5 EphemeronTables 180 17.6 Finalizers 181 Exercises 185 III The Standard Libraries 187 18 TheMathematicalLibrary 189 Exercises 190 19 TheBitwiseLibrary 191 Exercises 194 20 TheTableLibrary 195 20.1 InsertandRemove 195 20.2 Sort 196 20.3 Concatenation 197 Exercises 198 21 TheStringLibrary 199 21.1 BasicStringFunctions 199 21.2 Pattern-MatchingFunctions 201 21.3 Patterns 204 21.4 Captures 208 21.5 Replacements 209 21.6 TricksoftheTrade 213 21.7 Unicode 216 Exercises 218 22 TheI/OLibrary 221 22.1 TheSimpleI/OModel 221 22.2 TheCompleteI/OModel 224 22.3 OtherOperationsonFiles 228 Exercises 229 23 TheOperatingSystemLibrary 231 23.1 DateandTime 231 23.2 OtherSystemCalls 233 Exercises 235 24 TheDebugLibrary 237 24.1 IntrospectiveFacilities 237 24.2 Hooks 242 24.3 Profiles 243 Exercises 245 IV The C API 247 25 AnOverviewoftheCAPI 249 25.1 AFirstExample 250 25.2 TheStack 253 25.3 ErrorHandlingwiththeCAPI 258 Exercises 260 26 ExtendingYourApplication 261 26.1 TheBasics 261 26.2 TableManipulation 263 26.3 CallingLuaFunctions 267 26.4 AGenericCallFunction 269 Exercises 270 27 CallingCfromLua 273 27.1 CFunctions 273 27.2 Continuations 275 27.3 CModules 278 Exercises 280 28 TechniquesforWritingCFunctions 281 28.1 ArrayManipulation 281 28.2 StringManipulation 283 28.3 StoringStateinCFunctions 286 Exercises 292 29 User-DefinedTypesinC 293 29.1 Userdata 294 29.2 Metatables 296 29.3 Object-OrientedAccess 299 29.4 ArrayAccess 300 29.5 LightUserdata 301 Exercises 302 30 ManagingResources 305 30.1 ADirectoryIterator 305 30.2 AnXMLParser 307 Exercises 316 31 ThreadsandStates 319 31.1 MultipleThreads 319 31.2 LuaStates 323 Exercises 331 32 MemoryManagement 333 32.1 TheAllocationFunction 333 32.2 TheGarbageCollector 335 Exercises 338 Index 339 Preface When Waldemar, Luiz, and I started the development of Lua, back in 1993, we could hardly imagine that it would spread as it did. Started as an in-house languagefortwospecificprojects,currentlyLuaiswidelyusedinallareasthat canbenefitfromasimple,extensible,portable,andefficientscriptinglanguage, suchasembeddedsystems,mobiledevices,and,ofcourse,games. WedesignedLua,fromthebeginning,tobeintegratedwithsoftwarewritten in C/C++ and other conventional languages. This integration brings many benefits. Lua is a tiny and simple language, partly because it does not try to do what C is already good for, such as sheer performance, low-level operations, and interface with third-party software. Lua relies on C for these tasks. What Lua does offer is what C is not good for: a good distance from the hardware, dynamic structures, no redundancies, and ease of testing and debugging. For these goals, Lua has a safe environment, automatic memory management, and goodfacilitiesforhandlingstringsandotherkindsofdatawithdynamicsize. PartofthepowerofLuacomesfromitslibraries. Thisisnotbychance. After all, one of the main strengths of Lua is its extensibility. Many features con- tributetothisstrength. Dynamictypingallowsagreatdegreeofpolymorphism. Automaticmemorymanagementsimplifiesinterfaces, becausethereisnoneed to decide who is responsible for allocating and deallocating memory, or how to handleoverflows. Higher-orderfunctionsandanonymousfunctionsallowahigh degreeofparameterization,makingfunctionsmoreversatile. Morethananextensiblelanguage,Luaisalsoagluelanguage. Luasupports a component-based approach to software development, where we create an ap- plication by gluing together existing high-level components. These components arewritteninacompiled,staticallytypedlanguage,suchasCorC++;Luaisthe gluethatweusetocomposeandconnectthesecomponents. Usually,thecompo- nents (or objects) represent more concrete, low-level concepts (such as widgets and data structures) that are not subject to many changes during program de- velopment, and that take the bulk of the CPU time of the final program. Lua gives the final shape of the application, which will probably change a lot dur- ing the life cycle of the product. However, unlike other glue technologies, Lua is a full-fledged language as well. Therefore, we can use Lua not only to glue xiv Preface components, but also to adapt and reshape them, and to create completely new components. Of course, Lua is not the only scripting language around. There are other languages that you can use for more or less the same purposes. Nevertheless, Lua offers a set of features that makes it your best choice for many tasks and givesitauniqueprofile: Extensibility: Lua’sextensibilityissoremarkablethatmanypeopleregardLua notasalanguage,butasakitforbuildingdomain-specificlanguages. We designed Lua from scratch to be extended, both through Lua code and through external C code. As a proof of concept, Lua implements most of its own basic functionality through external libraries. It is really easy to interfaceLuawithC/C++,andLuahasbeenusedintegratedwithseveral other languages as well, such as Fortran, Java, Smalltalk, Ada, C#, and evenwithotherscriptinglanguages,suchasPerlandPython. Simplicity: Lua is a simple and small language. It has few (but powerful) concepts. This simplicity makes Lua easy to learn and contributes to its small size. Its complete distribution (source code, manual, plus binaries forsomeplatforms)fitscomfortablyinafloppydisk. Efficiency: Luahasaquiteefficientimplementation. Independentbenchmarks show Lua as one of the fastest languages in the realm of scripting lan- guages. Portability: Whenwetalkaboutportability,wearetalkingaboutrunningLua on all platforms we have ever heard about: all flavors of UNIX and Win- dows,PlayStation,Xbox,MacOSXandiOS,Android,KindleFire,NOOK, Haiku,QUALCOMMBrew,IBMmainframes,RISCOS,SymbianOS,Rab- bitprocessors,RaspberryPi,Arduino,andmanymore. Thesourcecodefor eachoftheseplatformsisvirtuallythesame. Luadoesnotuseconditional compilation to adapt its code to different machines; instead, it sticks to the standard ANSI (ISO) C. This way, you do not usually need to adapt it to a new environment: if you have an ANSI C compiler, you just have to compileLua,outofthebox. Audience Lua users typically fall into three broad groups: those that use Lua already embeddedinanapplicationprogram,thosethatuseLuastandalone,andthose thatuseLuaandCtogether. Many people use Lua embedded in an application program, such as Adobe Lightroom,Nmap,orWorldofWarcraft. TheseapplicationsusetheLua–CAPI to register new functions, to create new types, and to change the behavior of some language operations, configuring Lua for their specific domains. Fre- quently, the users of such applications do not even know that Lua is an inde- pendent language adapted for a particular domain. For instance, many devel- opers of plug-ins for Lightroom do not know about other uses of the language;

See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.