Lua Quick Start Guide - Gabor Szauer - E-Book

Lua Quick Start Guide E-Book

Gabor Szauer

0,0
23,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Lua is a small, powerful and extendable scripting/programming language that can be used for learning to program, and writing games and applications, or as an embedded scripting language. There are many popular commercial projects that allow you to modify or extend them through Lua scripting, and this book will get you ready for that. This book is the easiest way to learn Lua. It introduces you to the basics of Lua and helps you to understand the problems it solves. You will work with the basic language features, the libraries Lua provides, and powerful topics such as object-oriented programming. Every aspect of programming in Lua, variables, data types, functions, tables, arrays and objects, is covered in sufficient detail for you to get started. You will also find out about Lua's module system and how to interface with the operating system.
After reading this book, you will be ready to use Lua as a programming language to write code that can interface with the operating system, automate tasks, make playable games, and much more. This book is a solid starting point for those who want to learn Lua in order to move onto other technologies such as Love2D or Roblox.
A quick start guide is a focused, shorter title that provides a faster paced introduction to a technology. It is designed for people who don't need all the details at this point in their learning curve. This presentation has been streamlined to concentrate on the things you really need to know.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 213

Veröffentlichungsjahr: 2018

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Lua Quick Start Guide
The easiest way to learn Lua programming
Gabor Szauer
BIRMINGHAM - MUMBAI

Lua Quick Start Guide

Copyright © 2018 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 or its dealers and distributors, will be held liable for any damages caused or alleged to have been 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.

Commissioning Editor: Richa TripathiAcquisition Editor: Noyonika DasContent Development Editor: Roshan KumarTechnical Editor: Sushmeeta JenaCopy Editor: Safis EditingProject Coordinator: Hardik BhindeProofreader: Safis EditingIndexer:Aishwarya GangawaneGraphics:Jason MonteiroProduction Coordinator:Shantanu Zagade

First published: July 2018

Production reference: 1250718

Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.

ISBN 978-1-78934-322-9

www.packtpub.com

mapt.io

Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.

Why subscribe?

Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals

Improve your learning with Skill Plans built especially for you

Get a free eBook or video every month

Mapt is fully searchable

Copy and paste, print, and bookmark content

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 [email protected] for more details.

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.

Contributors

About the author

Gabor Szauer graduated from Full Sail University with a bachelor's degree in game development. He has been making video games professionally since 2010. He has worked on games for the Nintendo 3DS, Xbox 360, browser-based games, as well as games for iOS and Android. Gabor loves to teach, especially game development and programming. He has previously written the Game Physics Cookbook and is looking forward to producing much more content for those who want to learn.

"Give someone a program, you frustrate them for a day; teach them how to program, you frustrate them for a lifetime."
- David Leinweber

About the reviewer

Jayant Varma is an author of books on iOS development (Swift, Objective-C, and Xcode); Bash & Lua was his first book. He has been the technical editor for several Packt books. An academician at JCU, he mentored students for the Apple Swift Course at RMIT. He was the IT manager for BMW & Nissan, and as a development manager for an ASX-listed company, he contracted and built several mobile apps for small-to-large organizations in Australia. He has conducted workshops and spoken at meetups and events. He started OZApps and provides consulting and development services.

Packt is searching for authors like you

If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.

Table of Contents

Title Page

Copyright and Credits

Lua Quick Start Guide

Packt Upsell

Why subscribe?

PacktPub.com

Contributors

About the author

About the reviewer

Packt is searching for authors like you

Preface

Who this book is for

What this book covers

To get the most out of this book

Download the example code files

Download the color images

Code in Action

Conventions used

Get in touch

Reviews

Introduction to Lua

Technical requirements

What Lua is

Source code and binaries

Installing Lua on Windows 10

Installing Lua on macOS

Installing Lua on Linux

Tools for Lua

Installing VS Code on Windows 10

Installing VS Code on macOS

Installing VS Code on Linux

Exploring VS Code

Hello World!

Summary

Working with Lua

Technical requirements

Variables

Creating variables

Printing variables

Assigning variables

Comments

Basic types

nil

Boolean

number

Finding a type

String types

String literals

String length

Concatenate strings

String coercion

Escape characters

Console input

Scope

Scope access

Global scope

Shadowing

Functions

Defining a function

Calling a function

Function arguments

Any number of arguments

Returning a value

Returning multiple values

Operators

Arithmetic operators

Relational operators

Logical operators

Misc operators

Operator precedence

Control structures

if

elseif

else

Nesting if statements

Loops

while loops

Infinite loops

Breaking a loop

Repeat until loop

for loop

Nested loops

Summary

Tables and Objects

Technical requirements

Introduction to tables

Creating tables

Storing values

Table constructor

Tables are references

Arrays

Array constructor

Arrays are one-based

Sparse arrays

The size of an array

Multidimensional arrays

Iterating

Understanding pairs

Understanding ipairs

Closures

Iterator functions

Meta tables

setmetatable

getmetatable

__index

__newindex

rawget and rawset

__call

Operators

Math operators

Equivalence operators

Other operators

Objects

Classes

The : operator

Tables inside of objects

Inheritance

Single inheritance

Multiple inheritance

Summary

Lua Libraries

Technical requirements

The global table

Explicit variables

Dynamic variables

Environment

math

Trigonometry

Changing numbers

Comparing numbers

Randomness

Constants

Everything else

File IO

Opening a file

Writing data

Reading data

Reading line by line

Reading bits of data

Closing a file

Interfacing with the operating system

Working with time

Interacting with the shell

Working with files

More strings

Searching for a substring

Extracting a substring

Case manipulation

Creating and loading modules

Creating a module

Loading and using modules

Avoiding parsing

Executing files

Summary

Debugging Lua

Technical requirements

The debug library

Introspective information

The debug.getinfo return value

Filtering the information

Local variables

Hooks

Line ("l")

Call ("c")

Return ("r")

Setting a counter

Multiple hooks

Traceback

Debugger.lua

Using debugger.lua

Error-handling in Lua

pcall and error

assert

Profiling

The profile module

Using the profile module

Integrated development environments

LuaEdit

Breakpoints

Locals and Watch

Callstack

Decoda

Starting debugging

Everything else

Zero Brane Studio

Selecting an interpreter

Starting the debugger

Visual Studio Code

Summary

Embedding Lua

Technical requirements

Working with the C API

The stack

Pushing to the stack

Querying the stack

Reading from the stack

Stack size

Reading Lua variables from C

Loading a Lua file

Reading global variables

Example

Creating Lua variables from C

Calling Lua functions from C

Calling C functions from Lua

Working with tables in C

Reading values from a table

Writing values to a table

Meta tables

User data

Lua C API reference

Summary

Lua Bridge

Technical requirements

API conventions

Namespaces

Variables

Functions

Properties

Classes

Constructor

Subclass

Member variables, properties, and functions

Static variables, properties, and functions

Calling C functions from Lua

LuaRef

LuaRef and tables

Summary

Next Steps

Books

Programming In Lua

Learning Game AI Programming with Lua

LÖVE for Lua Game Programming

Lua Game Development Cookbook

Game Development with Lua

Beginning Lua Programming

Lua Programming Gems

Learn Lua for iOS Game Development

Game engines

LÖVE 2D

Defold

Corona

Leadwerks

Gideros

Urho 3D

Polycode

ShiVa

Game mods

Roblox

Garry's Mod

World Of Warcraft

Natural Selection 2

Don't Starve

Hack 'n' Slash

Scriptable software

CEGUI

Conky

Premake

Moho

Summary

Other Books You May Enjoy

Leave a review - let other readers know what you think

Preface

Lua is a small, powerful, and extendable programming language that can be used to learn to program, write games and applications, or as an embedded scripting language. This book is the easiest way to learn Lua; it introduces you to the basics of Lua and helps you understand the problems it solves.

You will work with the basic language features, the libraries Lua provides, and powerful topics such as object-oriented programming. Every aspect of programming in Lua—variables, data types, functions, tables, arrays and objects—is covered in sufficient detail for you to get started. You will also find out about Lua's module system and how to interface with the operating system.

After reading this book, you will be ready to use Lua as a programming language to write code that can interface with the operating system, automate tasks, make playable games, and much more. This book is a solid starting point for those who want to learn Lua and then move on to other technologies, such as Love2D, to make games.

Who this book is for

This book is for developers who want to get up and running with Lua. This book is ideal for programmers who want to learn to embed Lua in their own applications, and is also ideal for beginner programmers who have never coded before. Starting with an introduction to the Lua language, you will learn how to create variables and use loops and functions. You will learn advanced concepts, such as creating an object-oriented class system using only Lua tables. We look at the standard Lua libraries and learn how to debug Lua code. We will use Lua as an embedded scripting language and learn about the Lua C API in detail.

What this book covers

Chapter 1, Introduction to Lua, serves as an introduction to Lua by answering the question what is Lua? Next, the chapter walks the reader through downloading and installing the appropriate Lua binaries, as well as Visual Studio Code. Visual Studio Code is the code editor we will be using throughout this book to edit Lua files.

Chapter 2, Working with Lua, is a primer on the basics of the Lua language. For those who have not programmed before, this chapter teaches the basic concepts of programming, such as variables, loops, and functions. For the more experienced programmer reading the book, this chapter serves as an introduction to Lua's syntax.

Chapter 3, Tables and Objects, states that the most powerful features of Lua are its table and meta-table systems. Through these systems, the language it self can be extended. This chapter focuses on exploring what tables are, how they work, and how they can be used to extend the language to support concepts such as object-oriented programming.

Chapter 4, Lua Libraries, explains that Lua ships with a large and mature standard library. This chapter explores the functionality provided by the standard Lua libraries. The functionality exposed by the standard libraries allows us to do complicated math, work with files, and interface with the operating system.

Chapter 5, Debugging Lua, explains that Lua provides us with powerful debugging facilities that allow us to debug Lua code using Lua its-self. This chapter explores how to do this. In addition to exploring Lua's built-in debug facilities, optional tools that offer an intuitive and standard debugging interface are covered.

Chapter 6, Embedding Lua, discusses Lua's C API. This chapter covers all the API functions required to embed Lua into an existing application. Lua was designed to be an embeddable language, and therefore the C API is small, clean, and straightforward. By the end of the chapter, you will have mastered the Lua stack and will be able to work with Lua from C.

Chapter 7, Lua Bridge, explains that even though Lua's C API is simple, it's verbose. Doing basic tasks can take a lot of typing. Lua Bridge is a third-party Lua binding library that aims to make embedding Lua in C much easier and less verbose. All the Lua Bridge functionality needed for common tasks such as exposing functions, variables, or objects are covered in this chapter.

Chapter 8, Next Steps, explains that by now, you will have a solid grasp of the basics of programming, Lua, and the Lua C API. This chapter focuses on what you can do with all this new-found knowledge. Further books and learning resources are provided in this chapter. In addition to learning resources, some practical suggestions such as Lua-powered game engines and games that can be modified with Lua are made.

To get the most out of this book

This book assumes that the reader is proficient in using a computer running either Windows, macOS, or Linux.

For chapters one to five, no assumptions are made about the readers' programming knowledge or experience.

Chapters six and seven assume beginner to novice familiarity with C or C++.

Download the example code files

You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.

You can download the code files by following these steps:

Log in or register at

www.packtpub.com

.

Select the

SUPPORT

tab.

Click on

Code Downloads & Errata

.

Enter the name of the book in the

Search

box and follow the onscreen instructions.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR/7-Zip for Windows

Zipeg/iZip/UnRarX for Mac

7-Zip/PeaZip for Linux

The code bundle for the book is also hosted on GitHub athttps://github.com/PacktPublishing/Lua-Quick-Start-Guide. In case there's an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available athttps://github.com/PacktPublishing/. Check them out!

Download the color images

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: http://www.packtpub.com/sites/default/files/downloads/LuaQuickStartGuide_ColorImages.pdf.

Code in Action

Visit the following link to check out videos of the code being run:http://bit.ly/2AawDX5

Conventions used

There are a number of text conventions used throughout this book.

CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "Mount the downloaded WebStorm-10*.dmg disk image file as another disk in your system."

A block of code is set as follows:

html, body, #map { height: 100%; margin: 0; padding: 0}

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

[default]exten => s,1,Dial(Zap/1|30)exten => s,2,Voicemail(u100)

exten => s,102,Voicemail(b100)

exten => i,1,Voicemail(s0)

Any command-line input or output is written as follows:

$ mkdir css

$ cd css

Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "Select System info from the Administration panel."

Warnings or important notes appear like this.
Tips and tricks appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Reviews

Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packtpub.com.

Introduction to Lua

This chapter covers what Lua is and how to set up a Lua environment on any operating system. Lua is not tied to any operating system, so this chapter covers installing Lua for Windows, macOS, and Linux. By the end of this chapter, you will have a fully functional Lua development environment set up, regardless of what operating system you are using. This will leave you ready to start learning the Lua language.

This is what you will learn in this chapter:

What Lua is

How to install Lua

Available Lua tools

How to install Visual Studio Code

How to use Visual Studio Code

Write and run a Hello World Lua application

Technical requirements

You will berequiredto haveJavaScript programming language. Finally, to use the Git repository of this book, the user needs to install Git.

The code files of this chapter can be found on GitHub:https://github.com/PacktPublishing/Lua-Quick-Start-Guide/tree/master/Chapter01

Check out the following video to see the code in action:http://bit.ly/2NGKDty

What Lua is

Lua is a powerful, fast, lightweight, embeddable scripting language. The Lua virtual machine and interpreter are written in C. As a language, Lua is easy to learn. It contains 21 keywords, which makes the language rather small. Lua is also easy to read and understand, as its syntax makes it similar to English. For example, consider the following code snippet:

if not hero:IsAlive() then GameOver();end

This code is easy to read, and I bet you can take an intuitive guess at what it does. Lua is not only easy to read, it is also very powerful. The real power of Lua comes from its extensible nature. Programming constructs such as object-oriented programming (OOP) can be implemented in Lua, even though the language has no native support for objects.

At the time of writing, Lua has 14 versions; this book will focus on Lua 5.2.4. The latest version is 5.3; the main difference between 5.2 and 5.3 is that 5.3 contains support for explicit integers and bitwise operation.

While this book covers everything needed to get started with Lua programming, it never hurts to have more resources. The first edition of Programming In Lua can be read online, for free, at https://www.lua.org/pil/contents.html.

Source code and binaries

Lua is open source software published under the MIT License. You can browse Lua's source code at https://www.lua.org/source/. Additionally, you can download both the source code and reference manuals for Lua from https://www.lua.org/ftp/.

At the time of writing, no pre-built binaries are downloadable from the lua.org website. Pre-built binaries can be found on SourceForge at https://sourceforge.net/projects/luabinaries/. In this chapter, we will be using SourceForge to download binaries for Lua.

Installing Lua on Windows 10

Follow these steps to install Lua 5.2.4 on Windows 10. These instructions are written for Windows 10, but the steps needed to install should be similar on older (and future) versions of Windows as well:

To download Lua 5.2.4, visit

https://sourceforge.net/projects/luabinaries/files/5.2.4/

.

Click on the

Tools and Executables

link.

On a 32-bit version of Windows, click the

lua-5.2.4_Win32_bin.zip

link to start downloading Lua. On a 64-bit version of Windows, click the

lua-5.2.4_Win64_bin.zip

link to start downloading.

Once the file is downloaded, unzip the file. Unzipping the downloaded file should create four new files:

lua52.dll

,

lua52.exe

,

luac52.exe

, and

wlua52.exe

.

Create a new folder inside

C:\Program Files

, and call this new folder

LUA

. Copy the four files you just unzipped into this directory.

Rename

lua52.exe

to

lua.exe

. If your Windows installation is set up to hide file extensions, rename

lua52

to

lua

:

The path to Lua needs to be set up as an environment variable in Windows.

Right-click on the

Start/Windows

menu button and select the

System

option.

From the

System

window, select the

Advanced Settings

option.

Having clicked the

Advanced Settings

option, you should now see the

System Properties

dialog. In this dialog, click on the

Environment Variables...

button.

In the

Environment Variables

window, with the

Path

variable selected, click the

Edit...

button:

Inside the

Edit environment Variable

window, click the

New

button and add

C:\Program Files\LUA

as a new path. Click the

OK

button to save changes and close this window. You can close all the windows we have opened up to this point.

Lua should now be successfully installed on your computer. To verify the installation, you need to launch a new Command Prompt. You can launch Command Prompt by right-clicking the Windows

Start/Windows

button and selecting the

Command Prompt

item.

In the newly opened Command Prompt, type

lua -v

. If everything is set up correctly, the command should print out the installed version of Lua (5.2.4):

Installing Lua on macOS

Follow these steps to install Lua 5.2.4 on macOS. These instructions are written for macOS High Sierra, but the steps are the same on previous (and future) versions of macOS as well:

To download Lua 5.2.4, visit

https://sourceforge.net/projects/luabinaries/files/5.2.4/

.

Click on the

Tools and Executables

link.

Click on the

lua-4.2.4_MacOS1011_bin.tar.gz

link to start downloading Lua.

Once the zip file has downloaded, unzip it. The archive should contain two files,

lua52

and

luac52

:

Create a new folder in your

~/Documents

directory, and name this folder

LUA

. Move both

lua52

and

luac52

into this new directory:

Rename

lua52

to just

lua

.

Launch a Terminal window. The Terminal app is located at

/Applications/Utilities/Terminal.app

. You can also simply type

Terminal

into the universal search on macOS.

With the new Terminal window open, type

sudo nano /etc/paths

and hit

Enter

. You will be asked for your password; this is the password for your user account. The password will not show up as you type it. After the password is entered, nano will open; nano is a Terminal-based text editor. You should see something similar to the following window:

You can navigate the type cursor with the arrow keys. Don't worry if your

paths

file (the file we are editing) already has text in it. We will be adding a new entry into this file; where in the file you add the new entry does not matter. On a new line, type

~Documents/LUA

:

Press

Ctrl

+

X

to exit nano. The program will ask you if you want to save the changes you have made to the file. Press

Y

to save changes.

Nano will ask you to confirm the filename. Just hit

Enter

to accept the default path.

In order for the changes made in the paths to take effect, you must restart the Terminal app. To do this, right-click on the Terminal icon in your macOS dock and select

Quit

. Then, launch a new Terminal window.

In the new Terminal window, type

lua -v

. If everything is set up correctly, the Terminal should print out the installed version of Lua (5.2.4):