Make-Games-With-Love

Create A Ship

At the top of the main file add:

local ship

This way we define a local variable that will be our reference to the ship.

Since we need to set up some things like where on the screen the ship is and how it looks we need to give fill it with some content:

local ship = {
    name    = "USS Enterspace",
    health  = 100,
    x       = 0,
    y       = 0
}

The curly braces { } convey that a new container is made. This container is called table and is an associative array. This means that this is an efficient data structure made from index and value pairs. For example:

{ name = "USS Enterspace" }

Here name is the index(or key) and the string "USS Enterspace" is the value. The index and the value can be almost anything in Lua. Even another table.

What is your name?

We change the "hello world" in our previous example to the ships name:

function love.draw()
    love.graphics.print(ship.name, 200, 200)
end

Now the name of the ship is being printed onto the screen.

Change

We even change some attribute of our ship anytime:

local ship = {
    name    = "USS Enterspace",
    health  = 100,
    x       = 0,
    y       = 0
}

ship.name = "USS Spaceprice"

function love.draw()
    love.graphics.print(ship.name, 200, 200)
end

As you see now the name has changed again.

Remember: You can access and change table values by their indexname the with the . notation. For example: ship.name.

Coordinates

Our spaceship can fly left/right and up/down. This gives us 2 axes to move around. A position of the ship can be defined by 2 numbers: x and y.

If we want we can draw the text at the coordinates of the ship.

function love.draw()
    love.graphics.print(ship.name, ship.x, ship.y)
end

Now you can play around with the numbers in the ship table definition to change the place of the text.