Sei sulla pagina 1di 13

Beginning

Lua Programming
Kurt Jung and Aaron Brown

1 S O 7

WILEY
2 O O 7

Wiley Publishing, Inc.

Contents
Acknowledgments Introduction Chapter 1 : Getting Situated Choosing How to Install Lua Building Lua Yourself Selecting Prebuilt Lua Finding Your System's Shell
Windows Shells Shells on Unix and Unix-Like systems Shell Features The Environment Environment Variables on Unix-Like Systems Environment Variables on Windows

ix xxiii 1 1 2 3 3
3 3 4 4 4 5

Dealing with Tarballs and Zip Files Compiling Lua The Lua Source Tarball Compiling Lua on Linux and Other Unix-Like Systems Compiling Lua on Windows
Building Lua with Microsoft.Visual C++ Building Lua with the Tiny C Compiler Building Lua with MinGW

6 7 7 8 12
13 14 16

Binary Packages Selecting a Prebuilt Binary Package Installing a Prebuilt Binary Package on a Unix-Type System Installing a Prebuilt Binary Package on Windows Additional Tools Programmer's Editor Revision Control System Summary Chapter 2: First Steps

18 18 19 20 21 21 22 22 23 23 24 24 25

Numbers and Arithmetic Operations: Basic Interpreter Usage Addition, Subtraction, Multiplication, Division, and Exponentiation Interacting with the Interpreter Other Notations for Numbers

Contents
Interpreter Know-How Quitting the Interpreter Interpreter Shortcuts Numerical Gotchas Division by Zero and Overflow Floating-Point Rounding Variables and Assignment Assignment Basics Multiple Assignment Variables on the Right Side of Assignments Strings Quoting Strings Quoting Strings with Double Quotes Quoting Strings with Single Quotes Quoting Strings with Square Brackets Backslash Escaping Relational Operators and Boolean Values Comparing Numbers Comparing Strings The nil Value Boolean Operators The and Operator The or Operator The not Unary Operator The Concatenation, Length, and Modulo Operators The String Concatenation Operator The Length Operator The Modulo Operator Automatic Conversion of Operands Precedence and Associativity Variables and Values Comments Expressions and Statements Compound Statements The if Statement The while Loop The for Loop The repeat Loop / The break and do Statements ' Summary Exercises 26 26 26 27 27 28 28 29 31 32 32 32 32 33 33 35 37 37 38 40 41 42 43 44 45 45 46 47 48 49 51 52 53 54 55 58 60 62 63 66 66

XII

Contents
Chapter 3: Extending Lua with Functions Return Values Using a Function that Returns a Value Defining a Function that Returns a Value Using return to Alter Control Flow Returning Nothing Returning Multiple Values Adjusting Value Lists Using Multiple-Valued Functions in Value Lists Using Valueless Functions in Value Lists Chunks as Functions Variable Scope Actual and Formal Arguments Local Variables Understanding Side Effects Ordering Side Effects Short-Circuit Evaluation Functions Calling Functions The Call Stack Recursion Stack Overflow Tail Calls Functions as Values Replacing Built-in Functions Comparing and Printing Functions Function Definitions as Assignments Local Functions Whitespace, Semicolons, and Function Calls Upvalues and Closures Defining Functions that Create Functions Defining Functions with Private State Figuring Out Tricky Scope Situations Summary Exercises Chapter 4: Working with Tables Tables Introduced A Shorter Way to Write Some Keys Altering a Table's Contents Tables as Arrays Array Length 69 72 72 73 74 76 77 78 78 79 81 84 84 85 91 91 93 95 95 97 98 99 102 102 103 103 105 106 108 108 110 111 113 114 117 117 119 120 121 123

xiii

Contents
Looping through Tables Tables of Functions The Table Library table.sort table.concat table.remove table.maxn Object-Oriented Programming with Tables Functions with Variable Numbers of Arguments Defining Vararg Functions Scripts as Vararg Functions Keyword Arguments Different but the Same Table Equality Avoiding Bugs by Understanding Mutability Variables and Mutable Values Tables and Functions Copying Tables Building Other Data Structures from Tables Custom-Made Loops Global Variable Environments Summary Exercises 124 128 128 128 131 132 132 133 136 136 140 143 144 144 145 145 147 148 152 158 163 168 169

Chapter 5: Using Strings


Basic String Conversion Functions String Length Converting Between Characters and Character Codes Formatting Strings and Numbers with string.format Input/Output Writing to and Reading from a File Pattern-Matching Searching for a Specific String Matching Any of Several Characters Matches of Varying Lengths Captures Matching Balanced Delimiters More on string.find, string.match, and string.gsub Iterating Through All Matches Tricks for the Tricky Magic Characters Chart Summary

111
171 173 173 174 180 181 185 186 186 193 198 202 202 204 207 209 210

'

Exercises xiv

210

Contents
Chapter 6: Handling and Avoiding Errors Kinds of Errors Syntax Errors Runtime Errors Handling Errors Default Error Behavior Checking Assumptions Code Errors Data Errors The assert and error Functions Defining Your Own Error Condition Anticipating Error Conditions Working with Return Values Structuring Code Error-Containment Functions The pcall Function The xpcall Function User-Written Scripts Locating Errors Summary Exercises Chapter 7: Using Modules Interfaces and Implementations The require Function Where to Put Modules Creating a Module Directory Setting Lua's Environment Variable Preserving a Module's Interface Module Bookkeeping Bytecode Namespaces Creating and Reusing Namespaces Avoiding Global Variables Using the strict Module Reporting All Global Assignments The module Function C Modules Summary Exercises 213. 213 213 217 218 218 219 220 220 220 221 222 222 224 227 227 229 230 230 230 231 233 233 234 235 235 236 236 240 241 242 242 244 244 244 245 247 247 247

xv

Contents
Chapter 8: Extending Lua's Behavior with Metamethods Using Concatenation and Arithmetical Operators on Tables Relational Metamethods Indexing and Call Metamethods Non-Tables with Metamethods Non-Syntactical Metamethods Metamethod Applicability Summary Exercises Chapter 9: Handling Events Naturally with Coroutines Coroutines and Program Control
Coroutines Are Not Functions How Coroutines Are Like Programs
Coroutines Transfer Control Wrapping a Coroutine Coroutines Are Cooperative Outside Looking In Coroutines Have Status Rules of Conduct Work Shoulder-to-Shoulder Trust the Dispatcher Expect the Best, Prepare for the Worst Play on Your Side of the Fence Avoid the Deep End

249 249 257 258 265 267 . 268 268 269 271 271
272 272
273 273 273 275 278 279 279 280 280 280 281

Managing Concurrent Tasks Retaining State


Exercising a Coroutine's Memory Iterating with Coroutines Handling Events Simply The Event Loop Yielding to Another Coroutine

281 282
282 286 287 288 296

Summary Exercises Chapter 10: Looking Under the Hood Bytecode and luac Garbage Collection The Implementation of Tables and Strings

297 297 299 299 303 307

XVI

Contents
The Debug Library Inspecting and Manipulating Running Code Hooks Other Functions in the Debug Library Summary Exercises Chapter 1 1 : Exploring Lua's Libraries Core Library Environment Functions Metatable Functions Chunk-Loading Functions Error-Containment Functions Module Functions The Garbage-Collection Function Type and Conversion Functions Basic Output Error-Condition Functions Table Traversal Functions Vararg-Related Functions Coroutine Library Package Library String Library Pattern-Based String Functions String-Conversion Functions Table Library Math Library Trigonometric Functions Inverse Trigonometric Functions Hyperbolic Functions Exponent Functions Logarithm Functions Adjustment Functions Floating Point Representation Angle Conversion Functions Pseudo-Random Number Functions Modulus Functions Minimum and Maximum Functions Constants Input/Output Library 308 308 315 321 321 322 325 325 326 326 328 330 331 332 333 333 333 334 335 336 338 340 340 342 344 345 345 348 351 354 356 358 360 361 362 362 363 363 364

'

xvii

Contents
Operating System Library CPU Timing Time and Date Functions Filesystem Functions Other Operating System Functions Debugging Library Summary Chapter 1 2 : Using Community Libraries Library Overview Dynamically Linked Libraries
Resolving External References Configuration Options Libraries Built from Source Code Building Libraries on Unix-Like Systems Building Libraries on Windows Limits to Portability

368 368 368 369 370 370 373 375 375 376
376 376 377 378 378 379

How Lua Interacts with Libraries The Variable Registration Process Calling a C Function from Lua The pack Binary Structuring Library Building the pack Library on Unix-type Systems Building and Installing the pack Library on Windows Testing the pack Library Installing the pack Library Using the pack Library The cURL File Transfer Library Building libcurl Building libcurl on Unix-Like Systems Building libcurl on Windows Building luacurl Building luacurl on Unix-Like Systems Building luacurl on Windows Using luacurl The gd Graphics Library
Building gd Building gd on Unix-Like Systems Installing gd on Windows Building lua-gd Building lua-gd on Unix-Like Systems Building lua-gd on Windows Using lua-gd , '

379 379 380 383 383 384 384 385 385 389 389 390 391 392 392 393 393 395
395 396 396 397 397 398 399

xviii

Contents
The SQLite Database Library
Building SQLite3 Building SQLite3 on Unix-Like Systems Building SQLite3 on Windows Building Iua-sqlite3 Building Iua-sqlite3 on Unix-Like Systems Building Iua-sqlite3 on Windows Using Iua-sqlite3

405
405 405 406 407 407 408 409

Summary Exercises Chapter 13: Interfacing Lua with Other Languages How C Programs Use Lua
Embedding Lua Extending Lua Embedding or Extending: Which Is Best?

411 412 413 413


414 414 414

Communicating Between Lua and C Calling Lua from C


Obtaining a Lua Function Calling a Lua Function Protected Calls

415 421
421 421 422

Working with Userdata Indexing Values in C


Retrieving Indexed Values Setting Indexed Values

423 436
436 437

Retaining Values in C
The Registry C Function Environments Upvalues in C Referencing Values The Thread Environment

438
438 439 439 440 441

Layering Your Extension Library Summary Exercises Chapter 14: Managing Information with Databases Some Basic Relational Database Concepts SQL, LuaSQL, and MySQL Summary Exercises

441 447 448 449 449 458 466 466

XIX

Contents
Chapter 15: Programming for the Web A Web Server Primer Dynamic Web Content Embedded Web Server Extended Web Server Creating Content at Run Time with Lua Executing CGI Scripts CGI Scripts on Unix-Type Systems CGI Scripts on Windows Installing a Web Server Apache TinyWeb Testing Your Web Server with Static Content Serving Dynamic Web Content Problems with CGI Scripts Asynchronous Calls to the Server Producing a Calendar Dynamically Producing Charts Dynamically Interactive CGI Applications CGI Helper Routines Developing CGI Scripts Security Issues The Kepler Project CGI the Kepler Way Lua Pages Summary 467 467 468 468 469 469 469 470 470 471 All 472 474 474 475 476 478 481 489 489 498 498 498 499 500 501

'

Exercises
Chapter 16: Connecting to a Larger World Installing LuaSocket Compiling LuaSocket Compiling on Linux and Other Unix-Like Systems Compiling on Windows Installing Windows Binaries Network Overview Routed Packets Addresses Domain Names Identifying Internet Resources Transport Protocols Sockets: Streams and Datagrams TCP Socket Sociology XX

501
503 503 504 504 504 505 506 506 507 507 508 509 510 511

'

Contents
Using LuaSocket for Network Communication Handling Multiple Persistent Connections Using Lua Coroutines with the select Function Multiple Connections on the Server Side Setting Timeout Values for the Server Socket The Application Protocols Filtering the Flow of Data Accessing Web Pages Sending and Receiving E-mail Messages Networking with Lua and Streams On the Server Side: inetd and Friends On the Client Side: ssh and Friends Summary Exercises Chapter 1 7 : Programming Games with Lua Understanding Why and When to Use Lua Simple 2-D Action Game Using SDL Installing SDL and LuaCheia Using SDL Summary Exercise Chapter 1 8 : Carrying Lua with You Getting Started with Plua Obtaining Plua Examining the Distribution Contents Exploring Plua's Features Running the Plua Application Saving Plua Programs Reading the Online Documentation Using Palm OS Streams Compiling Applications Compiling Libraries Plua on the Mothership
The Command-Line Compiler The Palm OS Emulator Obtaining the Emulator Installing on Windows Configuring POSE Running Plua in the Emulator

512 518 518 522 523 524 524 527 529 536 536 538 541 542 543 543 544 544 546 562 562 565 565 566 566 567 567 569 570 571 572 573 576
576 577 577 578 578 578

xxi

Contents
Compiling a Program in the Emulator Exiting the Emulator The Palm OS Simulator Obtaining the Simulator Using the Simulator 580 580 581 581 581

Programming with Plua Generating Graphics Programming the User Interface Accessing Databases Summary Exercises Chapter 19: Fitting into the Lua Community The Lua Web Site The Lua Reference Manual Framing Questions The Lua Mailing List
Viewing and Searching the Archives Downloading the Archives Using a Web Browser to Access the List Using a Newsreader to Access the List Subscribing to the List Server Posting Messages

581 582 583 590 592 593 595 596 596 597 597
597 598 599 599 599 600

The Lua Chat Room Forums The Lua Wiki LuaForge Annual Workshops Summary Appendix A: Answers Index

601 601 601 602 603 603 605 629

xxii

Potrebbero piacerti anche