Coding With Lua

Andy Nguyen
9 min readApr 6, 2018

--

In the next blog I’ll get into some code for both LOVE and a game called Garry’s Mod, which have completely different syntax. As well as some Lua programming concepts which are applied to almost every Lua script/program regardless what program or engine they use, or if they even use one.

So from the previous blog, we learned how to install Lua and LOVE2D, which is a free open source game engine that works with Lua. Now we’ll go into some code.

Basic Lua

So let’s start by getting into some basic Lua code. First before we do start making some code, make sure the Lua Interpreter for the ZeroBrane IDE is on Lua:

Project > Lua Interpreter > Lua

If it is not on Lua, Lua 5.2 or Lua 5.3, it will not compile and run correctly.

To run the file, click on the double green arrows:

The highlighted icon.

Now let’s create some code, first let’s do a simple print with:

print “Hello World”

Output:

Hello World

You may notice that there are no parenthesis, if a function has a single input, and that input is either a String and a table, the function does not require there to be parenthesis. This is an interesting little quirk about functions within Lua but a majority of the time it will not apply and parenthesis should be used anyways like in a majority of programming languages.

Another note is that Lua does not need any semicolons to mark that it is the end of a line. From a previous blog post, Lua is a sequential language, this means that it will read line by line and there is no need for semicolons since it will read the code from top to bottom no matter what. This also means the coding conventions with Lua are going to be different from other languages as well.

Concatenation is slightly different within Lua than in other languages, they would use two periods compared to plus signs that are normally used in other programming languages, such as:

print(“Hello “ .. “Concat “ ..”World”)

Output:

Hello Concat World

Variables within Lua don’t need to be initialized, they are similar to locations (addresses) where data is stored. So if you try to print the contents of a variable, and you have not set any values to it, it will return a nil (similar to nulls in other languages) stating that it has nothing stored there. Variables also have no set datatype so it will store any data it is given regardless of datatype, so for operations or actions done to a variable, you must assume that the variable you are doing the action to is a specific datatype. You can also set a variable back to nil manually to clear whatever data is within it. The code below will show how a variable defaults to nil, how to set a value to a variable and clear a variable back to nil:

print(a)

a = 10

print(a)

a = “This String”

print(a)

a = nil

print(a)

Output:

nil

10

This String

nil

Functions within Lua are similar to those of other languages, with a name, return type, parameter, and the body of what it will do. Say we create a simple function, where it will take in a variable, add 10 to the variable, and return it. This function would look like the code below and we will run the function as well:

a = 10

a = myfunc(a)

print(a)

function myfunc(b)

b = b + 10

return b

end

But this will not run, why is that? There is a slight catch with Lua, and this is where the sequential aspect of Lua comes into play. You have to create the function before the function is called, unlike other programming languages which normally have their functions declared after they are used. Because Lua is sequential, reading from top to bottom, it has to read and create the function above where it is called and used. If it is the other way around, it will attempt to call a function it does not know exists yet. So the correct way to code this is:

function myfunc(b)

b = b + 10

return b

end

a = 10

a = myfunc(a)

print(a)

Now that we have covered some basics I’ll go over some LOVE2D and some more Lua related code and how they apply to LOVE2D.

Lua with LOVE2D

LOVE2D is a free open source game engine which allows you to use its functions and assets to great games within its engine. So the example I will be pulling code examples from is an example that comes with ZeroBrane, within the LOVE-samples folder. Before we start, we have to first set our Lua Interpreter to LOVE:

Project > Lua Interpreter > LOVE

You will also need to set the folder to be on the folder of the LOVE2D program you want to run, for this you will have to right click the folder you want to run > Project Directory > Set To Selected Directory:

Right Click > Project Directory > Set To Selected Directory

Now it will only show the folder you selected and any files within it, on the left side, for my example I will be going over the “shooter” folder:

Should only have one project/folder.

Now if you run it, it will load up a simple Space Invaders-esque game within a LOVE2D window:

Nice simple game.

If you look at the code, you may notice that some of the functions for the program start with a “love.”:

function love.load(arg)

function love.keyreleased(key)

function love.update(dt)

function love.draw()

These are LOVE2D specific functions that will only work if you are using LOVE2D. Like I have stated before, Lua uses assets of a program or engine and will usually use functions and variables from that program and it would only apply to that specific program.

Lua has tables “{}” which are similar to objects with attributes for languages like Java. Tables store multiple variables and datatypes within it, even another table, such as this code from the “shooter” example:

hero = {}

hero.x = 300

hero.y = 450

hero.width = 30

hero.height = 15

hero.speed = 150

hero.shots = {}

In this example it is a hero table that stores its x, y, witch, height, speed, and the shots of the hero within the table.

Another thing I will touch on are ipairs, from this code within “shooter”:

for i,v in ipairs(hero.shots) do

v.y = v.y — dt * 100

ipairs act similar to cursors in PL/SQL where it will will iterate through a table of variables and take each of those and pair them up with a variable, in this case “v”. So “i” will iterate from 1…n and “v” will iterate through variable shot1 … shotn. The next line of code will take the move each shot the hero has made up on the screen by (dt * 100). “dt” is the time different between two frames.

Now let’s jump into some Lua scripts for Garry’s Mod.

Lua with Garry’s Mod

First off let me say that you do need to own and install the game Garry’s Mod, if don’t own the game or able to install it, do not worry about this section too much. It is still good information to learn if you are interested in learning how to script for a game, but any code created will not be able to be tested. Also since Garry’s Mod is a program that uses Lua scripts, it already has a compiler and interpreter for Lua code, so you don’t even need to install Lua to be able to run these scripts within the game, instead we just have to know how to create the scripts.

Before we create a script, we need to create a file in the right location. So if you have the game installed, you need to navigate to the install directory of the game. It should look something like this:

“C:\Program Files (x86)\Steam\steamapps\common\GarrysMod\garrysmod”

There will be a folder called “addons”, open it and create a new folder within “addons”, name it something related to what you are making, in our case, we will be making an aimbot so I will name it “customAimbot”. Within the newly created folder, create another folder called “lua”, this is where we will store our script, or more than one if you use more than one. Now create a file, name it, and give it a “.lua” extension. Now open the file within any text editor, in my case I will user Notepad++.

So I will go over how to create a script for an Aimbot within the game. But before then I will go over a concept with Lua called Hooks. Hooks are a way of attaching a function to an event or action that happens within a program or engine, where it will run said function if a condition is met. For this case we will be using a hook like this:

hook.Add(“Think”,”aimbot”,aimbot)

Where the first parameter is the condition which will cause the function to run, the second parameter is a unique name for the hook, and the third is the name of the function that will run when the hook’s condition is met. So for this case, the function “aimbot” (third parameter) will run when the program has to “Think” (first parameter). Think is whenever the program has to run something, such as a refresh a frame, run a function, or any action. This is bad convention and in normal conditions should not be done as it will affect performance, but this is a simple and easy aimbot I am demonstrating.

Now lets go into the creation of the aimbot function, first lets create the function:

function aimbot()

end

Now we need to get the variables required for this, in this case we will need the player, and the traceline for the player. The traceline is where the player is looking, it will contain information such as the angle we are looking, the distance to what we are looking at, and the type of object we are looking at. This will be achieved by doing this:

function aimbot()

local player = LocalPlayer()

local trace = util.GetPlayerTrace( player )

local traceRes = util.TraceLine( trace )

end

Now we need to check if the target we are looking at is the world, or an entity (object) within the game world. We do this with an if statement that takes the trace for the player, and checks if the player is looking at something that isn’t the world, and then if it isn’t the world, it must be an entity. We will then take this entity and store it:

function aimbot()

local player = LocalPlayer()

local trace = util.GetPlayerTrace( player )

local traceRes = util.TraceLine( trace )

if traceRes.HitNonWorld then

local target = traceRes.Entity

end

end

Now that we have information on the target, we want to look up a specific part of the body, in this case, we will target “ValveBiped.Bip01_Spine2”, the upper chest area of the target. We then have to get the position of the target with GetBonePosition. This returns a position vector and an angle, we don’t need the angle but still need to have it returned somewhere. Then we set the players angle (aim) to the position of the target by getting the difference between the player and the target and getting the angle for this vector, then setting the player to aim at that angle. Lastly, add the hook at the end, so our final code should look like this:

function aimbot()

local player = LocalPlayer()

local trace = util.GetPlayerTrace( player )

local traceRes = util.TraceLine( trace )

if traceRes.HitNonWorld then

local target = traceRes.Entity

local targetpart = target:LookupBone(“ValveBiped.Bip01_Spine2”)

local targetpartpos,targetpartang = target:GetBonePosition(targetpart)

player:SetEyeAngles((targetpartpos — player:GetShootPos()):Angle())

end

end

hook.Add(“Think”,”aimbot”,aimbot)

Medium doesn’t allow me to format my pasted code very well but it should look something similar to this when formatted:

And that is how you make a simple aimbot. To run this script, start up Garry’s Mod load up a map. Open up the Developer Console (default key: ~) and type in lua_openscript_cl CustomAimbit.lua to start running the script. Now whenever you aim at an entity, and if it has the bone part specified, it will automatically snap to that body part and allow you to track it. The only way to turn off the script is to restart the map/local server you are running on for the game.

So overall for the blogs I went into some history with Lua, installation process for Lua, and some codes for Lua. I hope you enjoyed my blog posts and thank you for reading them.

--

--