📄 Page
1
(This page has no text content)
📄 Page
2
Beginning Lua Programming 01_069172 ffirs.qxp 1/2/07 7:52 PM Page i
📄 Page
3
01_069172 ffirs.qxp 1/2/07 7:52 PM Page ii
📄 Page
4
Beginning Lua Programming Kurt Jung and Aaron Brown 01_069172 ffirs.qxp 1/2/07 7:52 PM Page iii
📄 Page
5
Beginning Lua Programming Published by Wiley Publishing, Inc. 10475 Crosspoint Boulevard Indianapolis, IN 46256 www.wiley.com Copyright © 2007 by Wiley Publishing, Inc., Indianapolis, Indiana Published simultaneously in Canada ISBN: 978-0-470-06917-2 Manufactured in the United States of America 10 9 8 7 6 5 4 3 2 1 1MA/SS/QR/QX/IN Library of Congress Cataloging-in-Publication Data Jung, Kurt, 1956- Beginning Lua programming / Kurt Jung and Aaron Brown. p. cm. ISBN-13: 978-0-470-06917-2 (pbk.) ISBN-10: 0-470-06917-1 (pbk.) 1. Lua (Computer program language) I. Brown, Aaron, 1973- II. Title. QA76.73.L82J96 2007 005.13’3--dc22 2006036460 No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Cen- ter, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Legal Department, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4355, or online at http://www.wiley.com/go/permissions. LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS. THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION. THIS WORK IS SOLD WITH THE UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR OTHER PROFESSIONAL SERVICES. IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HERE- FROM. THE FACT THAT AN ORGANIZATION OR WEBSITE IS REFERRED TO IN THIS WORK AS A CITATION AND/OR A POTENTIAL SOURCE OF FURTHER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE PUBLISHER ENDORSES THE INFORMATION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMENDATIONS IT MAY MAKE. FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK MAY HAVE CHANGED OR DISAP- PEARED BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ. For general information on our other products and services please contact our Customer Care Department within the United States at (800) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002. Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Programmer to Programmer, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and other countries, and may not be used without written permission. All other trademarks are the property of their respective owners. Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this book. Lua 5.0 Copyright © 1994-2006, Lua.org, PUC-Rio Lua 5.1 Copyright © 2006, Lua.org The Lua logo was designed by Alexandre Nakonechnyj. Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books. 01_069172 ffirs.qxp 1/2/07 7:52 PM Page iv
📄 Page
6
About the Authors Between his first programs submitted to a Burroughs 5500 on Hollerith punch cards and his latest programs tapped into a Palm Pilot, Kurt Jung has been the principal programmer on various projects ranging from airline yield management to state machine–driven workflow. Aaron Brown began programming in elementary school on a Commodore 64. He plays various musical instruments and speaks Esperanto. 01_069172 ffirs.qxp 1/2/07 7:52 PM Page v
📄 Page
7
01_069172 ffirs.qxp 1/2/07 7:52 PM Page vi
📄 Page
8
Credits Acquisitions Editor Kit Kemper Development Editor Maryann Steinhart Technical Editor Adam Dumas Production Editor Rachel Meyers Copy Editor Kathryn Duggan Editorial Manager Mary Beth Wakefield Production Manager Tim Tate Vice President and Executive Group Publisher Richard Swadley Vice President and Executive Publisher Joseph B. Wikert Graphics and Production Specialists Denny Hager Shane Johnson Barry Offringa Heather Ryan Quality Control Technician John Greenough Jessica Kramer Project Coordinator Erin Smith Proofreading and Indexing Techbooks Anniversary Logo Design Richard Pacifico 01_069172 ffirs.qxp 1/2/07 7:52 PM Page vii
📄 Page
9
01_069172 ffirs.qxp 1/2/07 7:52 PM Page viii
📄 Page
10
Acknowledgments This project has had strong and capable guidance from Kit Kemper and Maryann Steinhart at Wiley Publishing. Maryann was remarkably responsive in making sure our questions were answered promptly. May Kit and Maryann land leading roles when Hollywood makes Beginning Lua Programming into a major motion picture. Laurels and commendations go to Adam Dumas, the best technical editor a book could possibly have. Adam’s thoroughness and attention to detail uncovered a humbling number of issues with the manuscript, all of which were brought to our attention in the most courteous and constructive way and often with insightful corrections. The Lua community provided much help and many answers. Thanks go to Roberto Ierusalimschy, Waldemar Celes, and Luiz Henrique de Figueiredo for creating a remarkable language about which it is easy to remain enthusiastic. Roberto and Luiz Henrique also answered some specific questions related to this book. The following people were very helpful in answering questions about their respec- tive projects: André Carregal (LuaForge and the Kepler Project), Mark Hamburg (Adobe Lightroom), Asko Kauppi (LuaSDL and LuaX), and Kein-Hong Man (ChunkSpy and the No-Frills Introduction to Lua 5.1 VM Instructions). From Kurt Jung: Collaborating with an individual as gifted and inventive as Aaron has been an entirely rewarding experience. It’s with great pleasure that I look forward to future projects together. Multajn dankojn, mia bonamiko. The encouragement of my mother and other family members has been greatly appreciated. Although writing this book may have given me a great excuse to delay various chores (most notably the one involving a lawn mower) and household repairs, it never interfered with the frequent, pleasurable, and bonding walks I take with my wife Maura, daughter Laura, and our bundle of canine energy, Brilla. I owe the greatest thanks to Maura for her support during this endeavor. From Aaron Brown: Apart from being my programming mentor, inviting me to collaborate on this book with him, and being an all-around nice guy, Kurt Jung is one of the few true kindred spirits I have encountered. Mia teraplano estas plena je angiloj! Cathy Lewis gave advice on the writing process at a pivotal moment. She (in her capacity as my girlfriend), my bandmates, and family also deserve thanks for their understanding of my reduced availability while slaving in the book mines. Special thanks to Mom (a.k.a. Marty Brown), who bought me that first computer so long ago. 01_069172 ffirs.qxp 1/2/07 7:52 PM Page ix
📄 Page
11
01_069172 ffirs.qxp 1/2/07 7:52 PM Page x
📄 Page
12
Contents Acknowledgments ix Introduction xxiii Chapter 1: Getting Situated 1 Choosing How to Install Lua 1 Building Lua Yourself 2 Selecting Prebuilt Lua 3 Finding Your System’s Shell 3 Windows Shells 3 Shells on Unix and Unix-Like systems 3 Shell Features 4 The Environment 4 Environment Variables on Unix-Like Systems 4 Environment Variables on Windows 5 Dealing with Tarballs and Zip Files 6 Compiling Lua 7 The Lua Source Tarball 7 Compiling Lua on Linux and Other Unix-Like Systems 8 Compiling Lua on Windows 12 Building Lua with Microsoft Visual C++ 13 Building Lua with the Tiny C Compiler 14 Building Lua with MinGW 16 Binary Packages 18 Selecting a Prebuilt Binary Package 18 Installing a Prebuilt Binary Package on a Unix-Type System 19 Installing a Prebuilt Binary Package on Windows 20 Additional Tools 21 Programmer’s Editor 21 Revision Control System 22 Summary 22 Chapter 2: First Steps 23 Numbers and Arithmetic Operations: Basic Interpreter Usage 23 Addition, Subtraction, Multiplication, Division, and Exponentiation 24 Interacting with the Interpreter 24 Other Notations for Numbers 25 02_069172 ftoc.qxp 1/2/07 7:52 PM Page xi
📄 Page
13
xii Contents Interpreter Know-How 26 Quitting the Interpreter 26 Interpreter Shortcuts 26 Numerical Gotchas 27 Division by Zero and Overflow 27 Floating-Point Rounding 28 Variables and Assignment 28 Assignment Basics 29 Multiple Assignment 31 Variables on the Right Side of Assignments 32 Strings 32 Quoting Strings 32 Quoting Strings with Double Quotes 32 Quoting Strings with Single Quotes 33 Quoting Strings with Square Brackets 33 Backslash Escaping 35 Relational Operators and Boolean Values 37 Comparing Numbers 37 Comparing Strings 38 The nil Value 40 Boolean Operators 41 The and Operator 42 The or Operator 43 The not Unary Operator 44 The Concatenation, Length, and Modulo Operators 45 The String Concatenation Operator 45 The Length Operator 46 The Modulo Operator 47 Automatic Conversion of Operands 48 Precedence and Associativity 49 Variables and Values 51 Comments 52 Expressions and Statements 53 Compound Statements 54 The if Statement 55 The while Loop 58 The for Loop 60 The repeat Loop 62 The break and do Statements 63 Summary 66 Exercises 66 02_069172 ftoc.qxp 1/2/07 7:52 PM Page xii
📄 Page
14
xiii Contents Chapter 3: Extending Lua with Functions 69 Return Values 72 Using a Function that Returns a Value 72 Defining a Function that Returns a Value 73 Using return to Alter Control Flow 74 Returning Nothing 76 Returning Multiple Values 77 Adjusting Value Lists 78 Using Multiple-Valued Functions in Value Lists 78 Using Valueless Functions in Value Lists 79 Chunks as Functions 81 Variable Scope 84 Actual and Formal Arguments 84 Local Variables 85 Understanding Side Effects 91 Ordering Side Effects 91 Short-Circuit Evaluation 93 Functions Calling Functions 95 The Call Stack 95 Recursion 97 Stack Overflow 98 Tail Calls 99 Functions as Values 102 Replacing Built-In Functions 102 Comparing and Printing Functions 103 Function Definitions as Assignments 103 Local Functions 105 Whitespace, Semicolons, and Function Calls 106 Upvalues and Closures 108 Defining Functions that Create Functions 108 Defining Functions with Private State 110 Figuring Out Tricky Scope Situations 111 Summary 113 Exercises 114 Chapter 4: Working with Tables 117 Tables Introduced 117 A Shorter Way to Write Some Keys 119 Altering a Table’s Contents 120 Tables as Arrays 121 Array Length 123 02_069172 ftoc.qxp 1/2/07 7:52 PM Page xiii
📄 Page
15
xiv Contents Looping through Tables 124 Tables of Functions 128 The Table Library 128 table.sort 128 table.concat 131 table.remove 132 table.maxn 132 Object-Oriented Programming with Tables 133 Functions with Variable Numbers of Arguments 136 Defining Vararg Functions 136 Scripts as Vararg Functions 140 Keyword Arguments 143 Different but the Same 144 Table Equality 144 Avoiding Bugs by Understanding Mutability 145 Variables and Mutable Values 145 Tables and Functions 147 Copying Tables 148 Building Other Data Structures from Tables 152 Custom-Made Loops 158 Global Variable Environments 163 Summary 168 Exercises 169 Chapter 5: Using Strings 171 Basic String Conversion Functions 171 String Length 173 Converting Between Characters and Character Codes 173 Formatting Strings and Numbers with string.format 174 Input/Output 180 Writing to and Reading from a File 181 Pattern-Matching 185 Searching for a Specific String 186 Matching Any of Several Characters 186 Matches of Varying Lengths 193 Captures 198 Matching Balanced Delimiters 202 More on string.find, string.match, and string.gsub 202 Iterating Through All Matches 204 Tricks for the Tricky 207 Magic Characters Chart 209 Summary 210 Exercises 210 02_069172 ftoc.qxp 1/2/07 7:52 PM Page xiv
📄 Page
16
xv Contents Chapter 6: Handling and Avoiding Errors 213 Kinds of Errors 213 Syntax Errors 213 Runtime Errors 217 Handling Errors 218 Default Error Behavior 218 Checking Assumptions 219 Code Errors 220 Data Errors 220 The assert and error Functions 220 Defining Your Own Error Condition 221 Anticipating Error Conditions 222 Working with Return Values 222 Structuring Code 224 Error-Containment Functions 227 The pcall Function 227 The xpcall Function 229 User-Written Scripts 230 Locating Errors 230 Summary 230 Exercises 231 Chapter 7: Using Modules 233 Interfaces and Implementations 233 The require Function 234 Where to Put Modules 235 Creating a Module Directory 235 Setting Lua’s Environment Variable 236 Preserving a Module’s Interface 236 Module Bookkeeping 240 Bytecode 241 Namespaces 242 Creating and Reusing Namespaces 242 Avoiding Global Variables 244 Using the strict Module 244 Reporting All Global Assignments 244 The module Function 245 C Modules 247 Summary 247 Exercises 247 02_069172 ftoc.qxp 1/2/07 7:52 PM Page xv
📄 Page
17
xvi Contents Chapter 8: Extending Lua’s Behavior with Metamethods 249 Using Concatenation and Arithmetical Operators on Tables 249 Relational Metamethods 257 Indexing and Call Metamethods 258 Non-Tables with Metamethods 265 Non-Syntactical Metamethods 267 Metamethod Applicability 268 Summary 268 Exercises 269 Chapter 9: Handling Events Naturally with Coroutines 271 Coroutines and Program Control 271 Coroutines Are Not Functions 272 How Coroutines Are Like Programs 272 Coroutines Transfer Control 273 Wrapping a Coroutine 273 Coroutines Are Cooperative 273 Outside Looking In 275 Coroutines Have Status 278 Rules of Conduct 279 Work Shoulder-to-Shoulder 279 Trust the Dispatcher 280 Expect the Best, Prepare for the Worst 280 Play on Your Side of the Fence 280 Avoid the Deep End 281 Managing Concurrent Tasks 281 Retaining State 282 Exercising a Coroutine’s Memory 282 Iterating with Coroutines 286 Handling Events Simply 287 The Event Loop 288 Yielding to Another Coroutine 296 Summary 297 Exercises 297 Chapter 10: Looking Under the Hood 299 Bytecode and luac 299 Garbage Collection 303 The Implementation of Tables and Strings 307 02_069172 ftoc.qxp 1/2/07 7:52 PM Page xvi
📄 Page
18
xvii Contents The Debug Library 308 Inspecting and Manipulating Running Code 308 Hooks 315 Other Functions in the Debug Library 321 Summary 321 Exercises 322 Chapter 11: Exploring Lua’s Libraries 325 Core Library 325 Environment Functions 326 Metatable Functions 326 Chunk-Loading Functions 328 Error-Containment Functions 330 Module Functions 331 The Garbage-Collection Function 332 Type and Conversion Functions 333 Basic Output 333 Error-Condition Functions 333 Table Traversal Functions 334 Vararg-Related Functions 335 Coroutine Library 336 Package Library 338 String Library 340 Pattern-Based String Functions 340 String-Conversion Functions 342 Table Library 344 Math Library 345 Trigonometric Functions 345 Inverse Trigonometric Functions 348 Hyperbolic Functions 351 Exponent Functions 354 Logarithm Functions 356 Adjustment Functions 358 Floating Point Representation 360 Angle Conversion Functions 361 Pseudo-Random Number Functions 362 Modulus Functions 362 Minimum and Maximum Functions 363 Constants 363 Input/Output Library 364 02_069172 ftoc.qxp 1/2/07 7:52 PM Page xvii
📄 Page
19
xviii Contents Operating System Library 368 CPU Timing 368 Time and Date Functions 368 Filesystem Functions 369 Other Operating System Functions 370 Debugging Library 370 Summary 373 Chapter 12: Using Community Libraries 375 Library Overview 375 Dynamically Linked Libraries 376 Resolving External References 376 Configuration Options 376 Libraries Built from Source Code 377 Building Libraries on Unix-Like Systems 378 Building Libraries on Windows 378 Limits to Portability 379 How Lua Interacts with Libraries 379 The Variable Registration Process 379 Calling a C Function from Lua 380 The pack Binary Structuring Library 383 Building the pack Library on Unix-type Systems 383 Building and Installing the pack Library on Windows 384 Testing the pack Library 384 Installing the pack Library 385 Using the pack Library 385 The cURL File Transfer Library 389 Building libcurl 389 Building libcurl on Unix-Like Systems 390 Building libcurl on Windows 391 Building luacurl 392 Building luacurl on Unix-Like Systems 392 Building luacurl on Windows 393 Using luacurl 393 The gd Graphics Library 395 Building gd 395 Building gd on Unix-Like Systems 396 Installing gd on Windows 396 Building lua-gd 397 Building lua-gd on Unix-Like Systems 397 Building lua-gd on Windows 398 Using lua-gd 399 02_069172 ftoc.qxp 1/2/07 7:52 PM Page xviii
📄 Page
20
xix Contents The SQLite Database Library 405 Building SQLite3 405 Building SQLite3 on Unix-Like Systems 405 Building SQLite3 on Windows 406 Building lua-sqlite3 407 Building lua-sqlite3 on Unix-Like Systems 407 Building lua-sqlite3 on Windows 408 Using lua-sqlite3 409 Summary 411 Exercises 412 Chapter 13: Interfacing Lua with Other Languages 413 How C Programs Use Lua 413 Embedding Lua 414 Extending Lua 414 Embedding or Extending: Which Is Best? 414 Communicating Between Lua and C 415 Calling Lua from C 421 Obtaining a Lua Function 421 Calling a Lua Function 421 Protected Calls 422 Working with Userdata 423 Indexing Values in C 436 Retrieving Indexed Values 436 Setting Indexed Values 437 Retaining Values in C 438 The Registry 438 C Function Environments 439 Upvalues in C 439 Referencing Values 440 The Thread Environment 441 Layering Your Extension Library 441 Summary 447 Exercises 448 Chapter 14: Managing Information with Databases 449 Some Basic Relational Database Concepts 449 SQL, LuaSQL, and MySQL 458 Summary 466 Exercises 466 02_069172 ftoc.qxp 1/2/07 7:52 PM Page xix