www.it-ebooks.info Beginning Lua Programming 01_069172 ffirs.qxp 1/2/07 7:52 PM Page i www.it-ebooks.info 01_069172 ffirs.qxp 1/2/07 7:52 PM Page ii www.it-ebooks.info Beginning Lua Programming Kurt Jung and Aaron Brown 01_069172 ffirs.qxp 1/2/07 7:52 PM Page iii www.it-ebooks.info 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 www.it-ebooks.info 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 www.it-ebooks.info 01_069172 ffirs.qxp 1/2/07 7:52 PM Page vi www.it-ebooks.info 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 www.it-ebooks.info 01_069172 ffirs.qxp 1/2/07 7:52 PM Page viii www.it-ebooks.info 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 www.it-ebooks.info [...]... Building lua- sqlite3 405 406 407 Building lua- sqlite3 on Unix-Like Systems Building lua- sqlite3 on Windows Using lua- sqlite3 407 408 409 Summary Exercises 411 412 Chapter 13: Interfacing Lua with Other Languages How C Programs Use Lua 413 413 Embedding Lua Extending Lua Embedding or Extending: Which Is Best? Communicating Between Lua and C Calling Lua from C Obtaining a Lua Function Calling a Lua Function... line that looks like the following: export LUA_ DIR=/usr/local/lib /lua/ 5.1 When you reference environment variables in shell scripts, you precede the name with $, as in echo $LUA_ DIR In this book, the following environment variables are recommended for Unix-like systems: LUA_ DIR=/usr/local/lib /lua/ 5.1 LUA_ CPATH=?.so; $LUA_ DIR/?.so LUA_ PATH=? .lua; $LUA_ DIR/? .lua Restart the shell for changes to take effect... 542 Chapter 17: Programming Games with Lua 543 Understanding Why and When to Use Lua Simple 2-D Action Game Using SDL 543 544 Installing SDL and LuaCheia Using SDL 544 546 Summary Exercise 562 562 Chapter 18: Carrying Lua with You Getting Started with Plua 565 565 Obtaining Plua Examining the Distribution Contents Exploring Plua’s Features 566 566 567 Running the Plua Application Saving Plua Programs... on Windows systems: UTIL_DIR=c:\program files\utility LUA_ DIR=c:\program files \lua\ 5.1 LUA_ CPATH=?.dll; %LUA_ DIR%\?.dll LUA_ PATH=? .lua; %LUA_ DIR%\? .lua The UTIL_DIR variable identifies the utility directory you created in the preceding section Additionally, if you have a software development kit and intend to compile Lua and possibly libraries for Lua, set the following environment variables: SDK_DIR=c:\program... describe data Lua Is an Implementation Lua is also a functioning software system A part of what we call Lua is an actual computer application that can interpret programs written in the Lua programming language The Lua interpreter is written in ANSI C, which because of its wide support, allows Lua to run on a vast spectrum of devices from highend network servers to small devices Both Lua s language... The Lua interpreter, typically named lua. exe in Windows and lua in Unix and friends, is a small command-line program that executes your scripts either interactively or noninteractively You’ll become familiar with the Lua interpreter and both of these modes in the first chapters of this book A note about these names: In this book, Lua refers to the Lua programming language or implementation, and lua. .. Building libcurl on Windows 390 391 Building luacurl 392 Building luacurl on Unix-Like Systems Building luacurl on Windows 392 393 Using luacurl 393 The gd Graphics Library 395 Building gd 395 Building gd on Unix-Like Systems Installing gd on Windows 396 396 Building lua- gd 397 Building lua- gd on Unix-Like Systems Building lua- gd on Windows 397 398 Using lua- gd 399 xviii www.it-ebooks.info Contents... first programming language In combination, these make Lua an attractive language for students and professionals alike The Facets of Lua Lua is, first and foremost, a tool for creating software You can use the standalone interpreter that is packaged with the Lua distribution to great advantage, and fit it seamlessly into your applications www.it-ebooks.info Introduction Lua Is a Programming Language Lua. .. to Install Lua 1 Building Lua Yourself Selecting Prebuilt Lua 2 3 Finding Your System’s Shell 3 Windows Shells Shells on Unix and Unix-Like systems Shell Features The Environment Environment Variables on Unix-Like Systems Environment Variables on Windows 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... program The Lua Source Tarball The contents of the Lua tarball are organized as follows: lua- 5.1.1 doc etc src test In the first level of this directory, you can read various text documents prepared by the Lua authors The README file explains what Lua is, the terms by which it is available, how to install it, and its origin The HISTORY file tracks the changes to the Lua language, its application programming . 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. 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. www.it-ebooks.info Beginning Lua Programming 01_069172 ffirs.qxp 1/2/07 7:52 PM Page i www.it-ebooks.info 01_069172 ffirs.qxp 1/2/07 7:52 PM Page ii www.it-ebooks.info Beginning Lua Programming Kurt