Lua Game Development Cookbook
By Mário Kašuba
()
About this ebook
- Discover how to solve common and less common problems in game mechanics
- Learn about modern computer graphics, sounds, physics, artificial intelligence and much more
- Packed with loads of practical examples, step-by-step instructions, and supporting explanations to help you build a modern game engine using Lua
This book is for all programmers and game enthusiasts who want to stop dreaming about creating a game, and actually create one from scratch.
The reader should know the basics of programming and using the Lua language. Knowledge of the C/C++ programming language is not necessary, but it's strongly recommended in order to write custom Lua modules extending game engine capabilities or to rewrite parts of the Lua code into a more efficient form.
Algebra and matrix operations are required in order to understand advanced topics in Chapter 4, Graphics – Legacy Method with OpenGL 1.x-2.1 and Chapter 5, Graphics – Modern Method with OpenGL 3.0+.
Sample demonstrations are coupled with binary libraries for Windows and Linux operating systems for convenience.
Related to Lua Game Development Cookbook
Related ebooks
Unreal Engine 4 Scripting with C++ Cookbook Rating: 0 out of 5 stars0 ratingsGame Physics Cookbook Rating: 0 out of 5 stars0 ratingsSwift Cookbook Rating: 5 out of 5 stars5/5Blender 3D: Characters, Machines, and Scenes for Artists Rating: 0 out of 5 stars0 ratingsOpenGL Development Cookbook Rating: 5 out of 5 stars5/5Android NDK Game Development Cookbook Rating: 0 out of 5 stars0 ratingsUnity UI Cookbook Rating: 0 out of 5 stars0 ratingsUnreal Development Kit Game Design Cookbook Rating: 0 out of 5 stars0 ratingsDirect3D Rendering Cookbook Rating: 0 out of 5 stars0 ratingsKivy Cookbook Rating: 0 out of 5 stars0 ratingsBlender 3D Cookbook Rating: 5 out of 5 stars5/5OpenGL 4 Shading Language Cookbook - Second Edition Rating: 0 out of 5 stars0 ratingsModern Python Cookbook Rating: 5 out of 5 stars5/5Windows Presentation Foundation 4.5 Cookbook Rating: 0 out of 5 stars0 ratingsLÖVE for Lua Game Programming Rating: 5 out of 5 stars5/5Procedural Content Generation for C++ Game Development Rating: 3 out of 5 stars3/5Learning C# by Developing Games with Unity 3D Beginner's Guide Rating: 5 out of 5 stars5/5Unity Game Development Essentials Rating: 5 out of 5 stars5/5Unity Android Game Development by Example Beginner's Guide Rating: 4 out of 5 stars4/5A Beginner's Guide to 2D Shooter Games: Beginners' Guides, #2 Rating: 0 out of 5 stars0 ratingsLearning Game AI Programming with Lua Rating: 0 out of 5 stars0 ratingsGodot from Zero to Proficiency (Foundations): Godot from Zero to Proficiency, #1 Rating: 5 out of 5 stars5/5Game Development with Swift Rating: 5 out of 5 stars5/5Building an FPS Game with Unity Rating: 0 out of 5 stars0 ratingsBuilding a Game with Unity and Blender Rating: 0 out of 5 stars0 ratingsLearning C++ by Creating Games with UE4 Rating: 3 out of 5 stars3/5Unreal Engine Physics Essentials Rating: 1 out of 5 stars1/5Unity 5.x Shaders and Effects Cookbook Rating: 0 out of 5 stars0 ratings
Software Development & Engineering For You
Kodi Made Easy: Complete Beginners Step by Step Guide on How to Install Kodi on Amazon Firestick Rating: 0 out of 5 stars0 ratingsLearn to Code. Get a Job. The Ultimate Guide to Learning and Getting Hired as a Developer. Rating: 5 out of 5 stars5/5Hand Lettering on the iPad with Procreate: Ideas and Lessons for Modern and Vintage Lettering Rating: 4 out of 5 stars4/5PYTHON: Practical Python Programming For Beginners & Experts With Hands-on Project Rating: 5 out of 5 stars5/5Managing Humans: Biting and Humorous Tales of a Software Engineering Manager Rating: 4 out of 5 stars4/5Gray Hat Hacking the Ethical Hacker's Rating: 5 out of 5 stars5/5How to Write Effective Emails at Work Rating: 4 out of 5 stars4/5Grokking Algorithms: An illustrated guide for programmers and other curious people Rating: 4 out of 5 stars4/5Python For Dummies Rating: 4 out of 5 stars4/5Agile Practice Guide Rating: 4 out of 5 stars4/5Beginning Programming For Dummies Rating: 4 out of 5 stars4/5SQL For Dummies Rating: 0 out of 5 stars0 ratingsFlow: A Handbook for Change-Makers, Mavericks, Innovators and Leaders Rating: 0 out of 5 stars0 ratingsKanban in Action Rating: 0 out of 5 stars0 ratingsThe Inmates Are Running the Asylum (Review and Analysis of Cooper's Book) Rating: 4 out of 5 stars4/5Hacking for Beginners: Mastery Guide to Learn and Practice the Basics of Computer and Cyber Security Rating: 0 out of 5 stars0 ratingsCoding with AI For Dummies Rating: 0 out of 5 stars0 ratingsiPhone Application Development For Dummies Rating: 4 out of 5 stars4/5Blender 3D Printing Essentials Rating: 0 out of 5 stars0 ratingsAfter Steve: How Apple Became a Trillion-Dollar Company and Lost Its Soul Rating: 4 out of 5 stars4/5iOS App Development For Dummies Rating: 0 out of 5 stars0 ratingsPython Handbook For Beginners. A Hands-On Crash Course For Kids, Newbies and Everybody Else Rating: 0 out of 5 stars0 ratingsThe Creative Programmer Rating: 0 out of 5 stars0 ratingsAndroid App Development For Dummies Rating: 0 out of 5 stars0 ratings
Reviews for Lua Game Development Cookbook
0 ratings0 reviews
Book preview
Lua Game Development Cookbook - Mário Kašuba
Table of Contents
Lua Game Development Cookbook
Credits
About the Author
About the Reviewer
www.PacktPub.com
Support files, eBooks, discount offers, and more
Why Subscribe?
Free Access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Sections
Getting ready
How to do it…
How it works…
There's more…
See also
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Basics of the Game Engine
Introduction
Preparing a basic file structure for the game engine
Getting ready
How to do it…
How it works…
Making a stack
Getting ready
How to do it…
How it works…
Making a queue
Getting ready
How to do it…
How it works…
Making a prioritized queue
Getting ready
How to do it…
How it works…
Extending ipairs for use in sparse arrays
Getting ready
How to do it…
How it works…
Creating Lua modules
Getting ready
How to do it…
A module that returns a table as an interface
A module in the form of an object
A module in the form of a singleton object
How it works…
Handling errors with pcall, xpcall, and assert
Getting ready
How to do it…
How it works…
Using Lua with existing projects written in C/C++
Getting ready
How to do it…
Initializing the Lua state
Creating a Lua module in C/C++
Passing variables from C/C++ into the Lua environment
Passing variables from the Lua environment to C/C++
Making the C++ class accessible from Lua with Lutok2
How it works…
Getting LuaSDL for libSDL 1.2
Getting ready
How to do it…
There's more…
Designing the main application loop with LuaSDL
Getting ready
How to do it…
How it works…
2. Events
Introduction
Processing input events with LuaSDL
Getting ready
How to do it…
Event handling with the if-then-else chain
Event handling with an associative array
How it works…
See also
Using the keyboard input
Getting ready
How to do it…
Normal keys
Modifier keys
How it works…
See also
Using the relative mouse position
Getting ready
How to do it…
There's more…
Using the absolute mouse position
How to do it…
Using timers
Getting ready
How to do it…
How it works…
There's more…
3. Graphics – Common Methods
Introduction
Creating a window in libSDL
Getting ready
How to do it…
How it works…
Creating surfaces
Getting ready
How to do it…
How it works…
There's more…
Surfaces manipulation
Getting ready
How to do it…
How it works…
Using colors
Getting ready
How to do it…
How it works…
Cursor manipulation
Getting ready
How to do it…
How it works…
See also
Initializing the graphics mode with OpenGL
Getting ready
How to do it…
How it works…
Getting OpenGL information
Getting ready
How to do it…
Getting the OpenGL version
Getting the graphic card vendor
Getting the graphic card name
Getting the extensions list
How it works…
Using OpenGL extensions with GLEW and Lua
Getting ready
How to do it…
How it works…
Loading images with SDL_image
Getting ready
How to do it…
How it works…
Creating textures
Getting ready
How to do it…
How it works…
There's more…
Loading and using bitmap fonts
Getting ready
How to do it…
How it works…
There's more…
See also
Loading and using TrueType fonts
Getting ready
How to do it…
How it works…
See also
Displaying the text
Getting ready
How to do it…
How it works…
See also
Creating texture atlas with the rover-design pattern
Getting ready
How to do it…
How it works…
Using tiles and tilesets in the game
Getting ready
How to do it…
How it works…
See also
4. Graphics – Legacy Method with OpenGL 1.x–2.1
Introduction
Drawing primitives in immediate mode
Getting ready
How to do it…
Drawing points
Drawing lines
Drawing line strips
Drawing line loops
Drawing triangles
Drawing triangle strips
Drawing triangle fans
Drawing quads
Drawing quad strips
Drawing polygons
How it works…
See also
Setting up blending
Getting ready
How to do it…
Additive blending
Subtractive blending
Alpha blending
How it works…
Moving, rotating, and scaling objects
Getting ready
How to do it…
How it works…
The identity matrix
The translation matrix
The scale matrix
The rotation matrix
There's more…
See also
Setting up the orthogonal and perspective cameras
Getting ready
How to do it…
The orthogonal mode
The perspective mode
How it works…
There's more…
See also
Setting up materials
Getting ready
How to do it…
How it works…
There's more…
See also
Setting up lighting
Getting ready
How to do it…
How it works…
There's more…
See also
Using display lists
Getting ready
How to do it…
How it works…
See also
Setting up the vertex buffer
Getting ready
How to do it…
How it works…
There's more…
5. Graphics – Modern Method with OpenGL 3.0+
Introduction
Loading and using GLSL shaders
Getting ready
How to do it…
How it works…
See also
Using uniform variables with shaders
Getting ready
How to do it…
Writing into uniform variables
Reading from uniform variables
How it works…
Writing a vertex shader
Getting ready
How to do it…
How it works…
There's more…
See also
Writing a fragment (pixel) shader
Getting ready
How to do it…
How it works…
There's more…
See also
Drawing primitives using vertex buffers
Getting ready
How to do it…
Vertex positions
Vertex colors
Vertex texture coordinates
How it works…
There's more…
See also
Rendering to texture
Getting ready
How to do it…
The render buffer with the color attachment
The render buffer with the depth attachment
How it works…
See also
Applying highlights and shadows to the scene
Getting ready
How to do it…
Vertex shader
Fragment shader
How it works…
See also
Bumpmapping
Getting ready
How to do it…
Vertex shader
Fragment shader
How it works…
There's more…
See also
6. The User Interface
Introduction
Drawing a simple window
Getting ready
How to do it…
How it works…
Moving the window
Getting ready
How to do it…
How it works…
Using the window hierarchy
Getting ready
How to do it…
Child window rendering
Event propagation
How it works…
See also
Showing the part of the window with the stencil test and window content scrolling
Getting ready
How to do it…
How it works…
See also
Window controls and interaction
Getting ready
How to do it…
Button
Edit box
How it works…
There's more…
See also
7. Physics and Game Mechanics
Introduction
Using Box2D with Lua
Getting ready
How to do it…
How it works...
Using vector math
Getting ready
How to do it…
How it works…
Choosing the correct vector scaling for the physics engine
Getting ready
How to do it…
How it works…
Creating static and dynamic objects
Getting ready
How to do it…
How it works…
There's more…
Setting up object properties
Getting ready
How to do it…
Movement damping
Object gravity scale
Fixed rotation
Object sleeping
Object mass and rotational inertia
Friction
Restitution
Density
How it works…
Moving objects
Getting ready
How to do it…
The continual force
Impulses
Object velocity information
How it works…
Setting up bullets
Getting ready
How to do it…
How it works…
Running the physics simulation
Getting ready
How to do it…
The fixed-time step
The dynamic-time step
How it works…
There's more…
Detecting object collision
Getting ready
How to do it…
How it works…
The beginContact callback
The endContact callback
The preSolve callback
The postSolve callback
There's more…
Setting up object collision filtering
Getting ready
How to do it…
How it works…
There's more…
Setting up object joints
Getting ready
How to do it…
Revolute joint
The prismatic joint
The distance joint
The rope joint
The weld joint
The pulley joint
The wheel joint
The gear joint
The motor joint
The mouse joint
The friction joint
How it works…
See also
8. Artificial Intelligence
Introduction
A simple pathfinding algorithm for a maze
Getting ready
How to do it…
Maze generation
Maze solving
How it works…
Pathfinding for tile-based environments with obstacles
Getting ready
How to do it…
How it works…
Heuristic
There's more…
See also
Using a fuzzy logic for decision making
Getting ready
How to do it…
A fuzzy set
A linguistic variable
A rule
A solver
A usage
How it works…
9. Sounds and Networking
Introduction
Initializing the audio subsystem
Getting ready
How to do it…
How it works…
Playing sound samples
Getting ready
How to do it…
How it works…
There's more…
See also
Playing background music
Getting ready
How to do it…
How it works…
See also
Network communication with ZeroMQ
Getting ready
How to do it…
How it works…
Creating a basic client-server architecture
Getting ready
How to do it…
The server part
The client part
How it works…
Sending messages to many hosts at once
Getting ready
How to do it…
The publisher part
The subscriber part
How it works…
Communication between threads
Getting ready
How to do it…
How it works…
Index
Lua Game Development Cookbook
Lua Game Development Cookbook
Copyright © 2015 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: July 2015
Production reference: 1200715
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-84951-550-4
www.packtpub.com
Credits
Author
Mário Kašuba
Reviewers
Victor Andrade de Oliveira
Anthony Zhang
Commissioning Editor
Sarah Cullington
Acquisition Editor
Kevin Colaco
Content Development Editor
Govindan K
Technical Editor
Vivek Arora
Copy Editors
Merilyn Pereira
Laxmi Subramanian
Project Coordinator
Sanjeet Rao
Proofreader
Safis Editing
Indexer
Rekha Nair
Graphics
Jason Monteiro
Abhinash Sahu
Production Coordinator
Manu Joseph
Cover Work
Manu Joseph
About the Author
Mário Kašuba achieved a master's degree in applied informatics at Slovak Technical University in Bratislava, where he used the Lua language in 3D robotics simulations and developed various multimedia applications along with a few computer games.
Currently, he is the co-owner and chief information officer of an IT Academy company, while he also leads courses on C/C++, PHP, Linux, Databases, Typo3, Silverstripe CMS, VMware virtualization, and the Microsoft Windows Server operating system.
He also works as the head web developer and system administrator for the web portal http://www.rodinka.sk/.
I would like to acknowledge the support provided by my family, friends, and colleagues. I am particularly grateful to the members of the Lua users community who helped me with the reviewing process. I would also like to thank the staff at Packt Publishing for their guidance and valuable support.
About the Reviewer
Victor Andrade de Oliveira is a Brazilian computer engineer who graduated from the Institute for Higher Studies of the Amazon (IESAM) with a vast knowledge of the Lua language and has worked for more than 5 years in the development of interactive and embedded applications for Ginga—the middleware of the Japanese-Brazilian Digital TV System (ISDB-TB) and ITU-T Recommendation for IPTV services.
Anthony Zhang is a programmer, electronics hobbyist, and digital artist who has an unhealthy obsession with robotics. If you want to hear him talk for hours on end, ask him something about AI, physical computing, obscure processor functionality, and computer graphics. These days, you'll find him working on video games, doing ridiculous things with microcontrollers, and attempting to add LEDs where they don't belong.
www.PacktPub.com
Support files, eBooks, discount offers, and more
For support files and downloads related to your book, please visit www.PacktPub.com.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.
Why Subscribe?
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Free Access for Packt account holders
If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access.
Preface
Game development is one of the most complex processes in the world as it requires a wide set of skills such as programming, math, physics, art, sound engineering, management, marketing, and many more. Even with modern technologies, it may take from a few hours to several years to create a game. This depends on the game complexity and tools available.
Computer games are usually based on a mix of simple concepts, which are turned into an enjoyable experience. The first step in making a good game is a game prototype. These can be made with the help of various game engines. However, learning how to use a game engine to the full extent may require you to study how it actually works. This way you have to rely on the available documentation and features that the game engine provides. Many game engines today provide a scripting language as a tool to implement certain game mechanics or to extend the game engine itself with new features.
The Lua programming language is gaining popularity in the game industry mainly due to its simplicity and efficiency. Most of the time, it's used only for simple tasks such as NPC dialogs, user interface, or custom game events. However, with additional Lua modules, you can create your own full-fledged game engine that can use almost all the capabilities of the modern computer hardware.
In this book, you'll find a set of recipes with solutions to the most common problems you may encounter while creating games with the Lua language.
The best way to learn something is to play with it. Therefore, each recipe is paired with simple demo applications that will help you understand the topic covered. You may even use these demo samples to create your own game prototype in no time.
All sample applications are available in the digital content of this book.
What this book covers
Chapter 1, Basics of the Game Engine, covers important algorithms and the basic design of a game engine written in the Lua programming language, as well as LuaSDL multimedia module preparation, which is the main part of all the recipes in this book.
Chapter 2, Events, deals with handling input events that are an important part of any game engine.
Chapter 3, Graphics – Common Methods, contains basic concepts used in computer graphics. You'll learn how to initialize the graphics mode, use basic OpenGL functions, load images, create textures, and draw text on the screen.
Chapter 4, Graphics – Legacy Method with OpenGL 1.x-2.1, explains how to use the intermediate mode of OpenGL, which is intended for use on older GPUs. Even when this mode is currently deprecated, it holds important information that is vital when using modern versions of OpenGL. It may be used as a precursor to more advanced topics in Chapter 5, Graphics – Modern Method with OpenGL 3.0+.
Chapter 5, Graphics – Modern Method with OpenGL 3.0+, covers the basics of using the GLSL shading language with the Lua language to draw various scenes. You'll also learn how to use per-pixel lighting, render into textures and apply surface effects with normal maps.
Chapter 6, The User Interface, covers the implementation of the custom user interface from simple windows to window controls.
Chapter 7, Physics and Game Mechanics, explains how to prepare and use the LuaBox2D module with the Lua language for physics simulation. The Box2D library is quite popular in modern side-scrolling games mainly because it offers great flexibility.
Chapter 8, Artificial Intelligence, deals with pathfinding algorithms and fuzzy logic. You'll learn how pathfinding works in games with simple maze or even tiled environments. More advanced topics cover decision making with fuzzy logic. In combination with pathfinding algorithms, you can create intelligent game opponents that won't jump into a lava lake at the first opportunity.
Chapter 9, Sounds and Networking, covers how to initialize the sound card, play sounds, and music. The second part covers network communication with the high-performance ZeroMQ library. It contains many improvements over traditional socket communication and it's used by companies such as AT&T, Cisco, EA, Zynga, Spotify, NASA, Microsoft, and CERN.
What you need for this book
Sample demonstrations for recipes require the Microsofts Windows or Linux operating systems. Unfortunately, Mac OS is not currently supported.
If you intend to build binary Lua modules from this book, you'll need the C/C++ compiler along with the recent version of the CMake building system. Additionally, Linux users will need to install development packages for the XOrg display server in order to include the graphical output.
However, it's not necessary to do so as binary Lua modules are included in code files for this book.
The recipes in Chapter 5, Graphics – Modern Method with OpenGL 3.0+, require a graphic card released after 2010 with support for OpenGL 3.3.
Who this book is for
This book is for all programmers and game enthusiasts who want to stop dreaming about creating a game, and actually create one from scratch.
The reader should know the basics of programming and using the Lua language. Knowledge of the C/C++ programming language is not necessary, but it's strongly recommended in order to write custom Lua modules extending game engine capabilities or to rewrite parts of the Lua code into a more efficient form.
Algebra and matrix operations are required in order to understand advanced topics in Chapter 4, Graphics – Legacy Method with OpenGL 1.x-2.1 and Chapter 5, Graphics – Modern Method with OpenGL 3.0+.
Sample demonstrations are coupled with binary libraries for Windows and Linux operating systems for convenience.
Sections
In this book, you will find several headings that appear frequently (Getting ready, How to do it, How it works, There's more, and See also).
To give clear instructions on how to complete a recipe, we use these sections as follows:
Getting ready
This section tells you what to expect in the recipe, and describes how to set up any software or any preliminary settings required for the recipe.
How to do it…
This section contains the steps required to follow the recipe.
How it works…
This section usually consists of a detailed explanation of what happened in the previous section.
There's more…
This section consists of additional information about the recipe in order to make the reader more knowledgeable about the recipe.
See also
This section provides helpful links to other useful information for the recipe.
Conventions
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: We can include other contexts through the use of the include directive.
A block of code is set as follows:
local sum_of_numbers = 0
local iterations = 3
for i=1,iterations do
sum_of_numbers = sum_of_numbers + 1/iterations
print((%f
):format(sum_of_numbers))
end
-- is the result equal to 1?
print(Sum equals to 1?
, sum_of_numbers == 1)
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
gl.Begin(gl_enum.GL_LINES
)
-- A
gl.Color4f(1, 0, 0, 1)
gl.Vertex3f(-0.5, -0.5, 0)
-- B
gl.Color4f(0, 1, 0, 1)
gl.Vertex3f(0.5, -0.5, 0)
-- C
gl.Color4f(0, 0, 1, 1)
gl.Vertex3f(0.5, 0.5, 0)
-- D
gl.Color4f(1, 1, 0, 1)
gl.Vertex3f(-0.5, 0.5, 0)
gl.End()
Any command-line input or output is written as follows:
mkdir luagl/build cd luagl/build cmake ..
New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: You can validate settings by pressing the Configure button
Note
Warnings or important notes appear in a box like this.
Tip
Tips and tricks appear like this.
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply e-mail <feedback@packtpub.com>, and mention the book's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Customer support
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
Downloading the example code
You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
Errata
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at <copyright@packtpub.com> with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
Questions
If you have a problem with any aspect of this book, you can contact us at <questions@packtpub.com>, and we will do our best to address the problem.
Chapter 1. Basics of the Game Engine
In this chapter, we will cover the following recipes:
Preparing a basic file structure for the game engine
Making a stack
Making a queue
Making a prioritized queue
Extending ipairs for use in sparse arrays
Creating Lua modules
Handling errors with pcall, xpcall, and assert
Using Lua with existing projects written in C/C++
Getting LuaSDL for libSDL 1.2
Designing the main application loop with LuaSDL
Introduction
Almost every game uses a game engine to help developers in video game production. It is usually used as a base platform for the game and manages all important functions from 2D/3D graphics, physics, sound effects, and network communication to artificial intelligence, scripting, and support for various software/hardware platforms. Using the scripting language in games has gained a lot of attention in the last decade mainly because it allows you to create game prototypes faster, easier, and it's an important part of the so-called modding support for the game community.
For instance, you can look at Quake game from the id software company, which uses its own scripting language Quake C and is one of the reasons why there are so many mods for this game. However, the source code for this language must be compiled before using. Depending on the project size this means a significant amount of time spent between feature implementation and testing. The Lua language can be used without prior compilation, which allows developers to test out their code right away.
The first game that used the Lua language for scripting was Grim Fandango from the company LucasArts. It was successfully used in further major game titles and today it can be commonly found in many multiplatform and mobile games.
Modern game engines are one of the most complex applications that are used. This leads to the situation where game developers use game engine as a black box without knowing how it actually works. For certain game titles, this might work out quite well. However, if you want to make a quick game prototype with certain features that are not present in the game engine, you'll most probably have to write your own game engine extension or find a workaround.
Lua language is fast and mature enough to be used as a game engine base language. Time-critical portions of a code can be written in C or C++ language and accessed via a Lua/C language interface. With this approach, you can view the Lua language as a high-level glue for the game engine process design.
This book will use Lua 5.1 version mainly because it's well supported and the existing code can be ported into a newer version with minor changes. Another reason behind this choice is that Lua 5.1 API is used in LuaJIT which is Just-In-Time implementation of Lua language. It's generally regarded as a faster version of the Lua language, which gives you speed comparable to compiled C code.
Lua language itself doesn't provide access to graphical output, sound devices or even input devices except basic I/O file interface. This shortcoming can be overcome with the use of LuaSDL binding to libSDL multimedia library that gives us the