Leadwerks Game Engine

Leadwerks Game Engine

99 valoraciones
Introduction to Lua
Por Aggror y 1 colaboradores
This guide is an introduction to Lua.
2
   
Premio
Favoritos
Favorito
Quitar
Introduction to Lua
Welcome to the world of making games. In this guide you will be taught the basics of the Lua scripting language in combination with the Leadwerks engine.

Example scripts
This document has several example scripts that you can copy in its entirely to the app.lua script. The App.lua script can be found in your project’s ‘/Script’ folder. The following example will lead to the screenshot below:
function App:Start() System:Print("Hello world.") end



What is a variable?
A variable is a piece of computer memory where you store information in. A variable has a name and a value. This value can be anything you want: a name, the amount of bullets your weapon has or the speed at which you are walking. The syntax to create a variable is as follows:

variableName = value

The variable name can't start with a number, but after that you can use whatever character you want. The '=' character means "assigning a value to the variable". Here are some examples of what kind of data you can assign to a variable
myVariable1 = 9 myVariable2 = 6.78 myVariable3 = "Hello world" myVariable4 = true

No semi colon
Maybe you have had a look at other scripting and programming languages and you might have noticed that Lua is not using semicolons. There is no need to end each line with a semicolon although it can be used to break up lines of code. This way you don't have to dedicate a whole line to a small declaration.
x = 10 ; y = 10;

if statement
"if" statements are used to 'check' if a requirement is met. If that is the case, then the code part of the if statement is executed. If it is not the case, the code will be skipped. The syntax looks as follow:
if requirement == true then --the code that gets executed end

As an example we can the following. If 'myVariable' is equal to '9', then the statement is true and the code inside body is executed.
function App:Start() myVariable = 9 if myVariable == 9 then System:Print("The statement was true ") end end

else statement
The else statement has to be used in combination with an if statement. We can simply say: if the first statement was not true, then executed this code.
function App:Start() myVariable = 8 if myVariable == 9 then System:Print("The statement was true ") else System:Print("The statement was not true ") end end


elseif
You if you want to have multiple if statements after each other, you can use the 'if else' statement. The ’if else’ statement can only be used if an 'if' statement has already been used. Have a look at the example: The first if statement is not true since 'myVariable' has the value of '7' and not '9'. That means we go to the next statement which is the first 'else if' statement. We are saying here: "if myVariable is bigger than 5, execute this code". This statement is true, which means the text "The value of ' myVariable ' is higher than 5.", is being printed to the screen. Now that we had a successful statement, Lua knows that it is done with checking this entirely list of statements. This means that the 'else' statement doesn't have to be executed.
function App:Start() myVariable = 7 if myVariable == 9 then System:Print("The value of ' myVariable' is 9.") elseif myVariable > 5 then System:Print("The value of ' myVariable ' is higher than 5.") else System:Print("The statement was not true ") end end

Operators
We have already seen some of them in action in the examples above: operators. Operators are special characters that tell Lua a comparison has to be made. Operators are often used in if statements. Here are the common operators that you need to know as a beginner:

== Equals To. (Pay attention to the difference of '=' and '=='. A single '=' means "assigning", while a double '==' means "equal to")
< Smaller than
<= Smaller than or equal to

> Larger than
>= Larger than or equal to
~ not : for instance: if myVariable ~= 5 then, We are saying if myVariable is not equal to 5



While loop
The while loop is a statement that keeps on looping over its code until a certain requirement is trye. The syntax of a while loop is as follows:

While requirement == true do --Do stuff end

In the example below the text will be printed to the screen until the while condition is no longer true.
function App:Start() x = 0 while x < 10 do System:Print("x has the following value: " .. x) x = x+1 end end

For loop
The for loop looks a lot like the while loop. The difference is that you determine the startingpoint, the value to reach and the increment (or decrement) value. This is what a for loop looks like:
function App:Start() for i = 0, 10, 2 do System:Print ( i ) end end

Notice in the Lua for loop that exit condition is always less than or equal to <= so be careful!

Concatenation
There are no +=, -=, /=, or *= operators in Lua.
String concatenation uses ".." instead of +

myAge = 99 System:Print( "I am ".. myAge .. " years old.")
Comments
If you want to comment out a part of your code you can simply do so. Code that is commented will be skipped by the engine. Comments in Lua go as follows:
--Single line comment --[[ multi line comment multi line comment ]]-- 
Tables
Tables
Sometimes you have a lot of information that you want to store in a ‘collection’ . In Lua you do this with tables. Lua uses tables for everything, instead of arrays and maps. (A table is basically a map though.)

-- tables are declared with {} local myTable={}

-- adding information to the table can be done like this
local myTable={"Tim", "Tommy", 5, 78}

-- Or like this. Where the number between the square brackets is the index
local myTable={} myTable[1]= "Tim" myTable[2]= "Tommy" myTable[3]= 5 myTable[4]= 78

You can add specific keys and values to a table like this:
local myTable = {} myTable.idle = 0 myTable.walk = 1 myTable.chase = 2

Looping through a table
Sometimes you want to loop through an entire table. You can do this with ‘pair’ or ‘ipair’. The first example below shows you how pairs iterating works. Unlike pairs, it only gives you the consecutive integer keys from 1, and it guarantees their order. With pairs, the number keys will not necessarily be given in the correct order!
function App:Start() --ipair local myTable={"Tim", "Tommy", 5, 78} for key,value in ipairs(myTable) do System:Print( key .. " has the value: " .. value) end local myTable = {} myTable.idle = 0 myTable.walk = 1 myTable.chase = 2 for key,value in pairs(myTable) do System:Print( key .. " has the value: " .. value) end end


Table insert
You can influence how new variables or objects are added to your table with the ‘table.insert’ command.
The syntax of for the insert command is as follows:
table.insert( tableName, index, value)

The example below show how the character ‘b’ is added to the table at index 2.
function App:Start() local myTable={"a", "c"} table.insert(myTable, 2, "b" ) for key,value in pairs(myTable) do System:Print( key .. " has the value: " .. value) end end

Table Size
Then if you want to know the size of the table use the symbol #
function App:Start() local myTable={} myTable[1]= "Tim" myTable[2]= "Tommy" myTable[3]= 5 myTable[4]= 78 System:Print(#myTable) end


Variable scopes
When making a script it is important to understand when a variable is local or global.
-- SCRIPT 1 local myNumber = 5 --local yourNumber = 8 --global self.ourNumber = 9 --local System:Print(myNumber ) --prints 5 System:Print(yourNumber) -- prints 8 System:Print(self.ourNumber ) -- prints 9 System:Print(ourNumber ) -- Doesn't work because it does not exist -- SCRIPT 2 System:Print(myNumber ) -- Doesn't work because script 2 doesn't have this variable System:Print(yourNumber) -- prints 8 since it is a global variable System:Print(self.ourNumber ) -- Doesn't work because script 2 doesn't have this variable System:Print(ourNumber ) -- Doesn't work because it does not exist


Accessing variables and function of other scripts
You can access all the script values and functions directly as shown below:
object:SetScript("Scripts/myScript.lua") object.script.someValue = 10 -- access variables object.script:MyFunction() -- access functions


Be sure to check to make sure entity.script is not nil, which is the case until a script is attached:
if entity.script~=nil then if type(entity.script.Kill)=="function" then entity.script:Kill() end end
14 comentarios
ShadowDragon_79 13 FEB 2023 a las 7:39 p. m. 
Hmm...
I do see that "self.ourNumber = 9" is part of an object; but since that object doesn't seem to be declared as local, why is this declaration then supposed to be so?

Or are objects automatically assumed to be local if not stated otherwise?
GrungeBro 24 DIC 2020 a las 1:49 p. m. 
i just wanna know how this language and examples relate to actual engine uses since the engine uses different functions and calls
LavaJava 13 MAY 2019 a las 7:20 a. m. 
While looping occurs while other lines of code are still cycling?, or does the while loop(loop inside the normal Looping) Say I want to play a certain score of music while my PC is within 50 game units of a scary house, should I while loop that code or will it work within its normal loop? Rephrase - can you have more than one loop in your code looping at the same time?
LavaJava 13 MAY 2019 a las 7:05 a. m. 
thank you the Z best LUA guide ever, keep the hits coming. You should teach a LUA course with a focus on basic AI scripts.
banger705 25 SEP 2018 a las 1:51 p. m. 
how do you excute the scripted? i added one an the only way i see this been done is to added object/enternity. the script is for the skyboxes
VideoGameRate 6 MAY 2018 a las 8:48 a. m. 
It's important to mention that indexing starts at 1 in Lua and not 0 as seen in other languages.
chris.palusak 14 MAR 2017 a las 10:05 a. m. 
This just a bunch of letters and numbers as far as im concered a bunch of mobo jumbo that doesnt make sence to me.
oddflavour 12 AGO 2014 a las 8:43 p. m. 
"The variable name can't start with a letter, but after that you can use whatever character you want."
My perfectionist soul won't let me rest.
nut around the corner 10 MAY 2014 a las 12:59 a. m. 
Perfect timing! I wanted to learn Lua so thank you!
Vileoxe 22 FEB 2014 a las 12:46 p. m. 
Good stuff here :)