Search code examples
lualove2d

Lua LÖVE automate variable names


I'm writing a lua LÖVE program as a school project.

The task is something about ants, that need to find food, take some to the nest they came from and on the way leaving a trace of pheromons. In addition we've write a program visualizing the process. For 100 ants, 5 food sources and all this in a space of 500x500 squares

I chose lua LÖVE for the visualization and wrote the following code:

function love.load()
    p = 500 -- Starting position

    xNest, yNest = p, p -- Initializing nest position

    xAnt1, yAnt1 = p, p -- Initializing ant position
    xAnt2, yAnt2 = p, p


end

-- Changes position every frame.
function love.update(dt)

-- AntI // See what I did there?
    xAnt1 = xAnt1 + math.random (-2, 2) -- Change position by a random number between 2 steps forward and 2 steps backward
    yAnt1 = yAnt1 + math.random (-2, 2) -- Change position by a random number between 2 steps sideways

    xAnt2 = xAnt2 + math.random (-2, 2) 
    yAnt2 = yAnt2 + math.random (-2, 2)
end



-- Draw ants and nest.
function love.draw()

    -- Nest 
    love.graphics.setColor(0, 255, 255) -- set drawing color green
    love.graphics.rectangle("line", xNest, yNest, 2, 2) -- draw a nest at xNest, yNest with a size of 2x2

    -- Ant
    love.graphics.setColor(255, 255, 255) -- set drawing color white
    love.graphics.rectangle("line", xAnt1, yAnt1, 2, 2) -- draw an ant at xAnt(number of ant), yAnt(number of ant) with a size of 2x2
    love.graphics.rectangle("line", xAnt2, yAnt2, 2, 2)

end

Since my task is to do what I did in xAntX, yAntX = p, p 100 times, whereby X I mean the number for the ant, I need some kind of loop that creates xAntX, yAntX = p, p, xAntX = xAntX + math.random (-2, 2) , yAntX = yAntX + math.random (-2, 2) and love.graphics.rectangle("line", xAntX, yAntX, 2, 2 a 100 times.

I tried a for loop, but it always yelled at me for trying to append a variable ´i´ to the initialization xAnt .. i, yAnt .. i and then count i++ with i = i + 1.


Solution

  • Make xAnt and yAnt tables, and access individual entries as xAnt[i] and yAnt[i].