Page 1 of 1

assigning table.remove to a variable then using it to print a number

Posted: Fri Jul 21, 2017 7:06 pm
by mustafatouny
The purpose of code is to randomly place flowers, The full tutorial is here
Image

Code: Select all

grid = {}
for y = 1, 14 do
 grid[y] = {}
 for x = 1, 19 do
  grid[y][x] = {flower = false}
 end
end
    
local possibleFlowerPositions = {}
for y = 1, 14 do
 for x = 1, 19 do
  table.insert(possibleFlowerPositions, {x = x, y = y})
 end
end
    
for flowerIndex = 1, 40 do
 local position = table.remove(possibleFlowerPositions, love.math.random(#possibleFlowerPositions))
 grid[position.y][position.x].flower = true
end
First, In the last line, Both of "position.y" and "position.x" must be numbers in order to indicate a cell in grid table (or array, doesn't know precisely), But I don't get how did it come by that way.

Second, I've searched in "Programming in Lua, Forth Edition" book and did some google but had never seen something like this before, so, If you were at my position what would you do to deal with this problem otherwise asking someone directly?

Re: assigning table.remove to a variable then using it to print a number

Posted: Fri Jul 21, 2017 9:08 pm
by bartbes
I'm not quite sure what you're asking, but I think you're asking why that code works?

So first of all, you've got a loop filling possibleFlowerPositions with.. well, possible flower positions. So possibleFlowerPositions is a table containing other tables, and those tables have an x and a y member containing a number each.

Then, if you look at table.remove in the manual, you can see that it removes an element from the table at the specific index and returns the removed value. Since you pass in a random index, this means you'll pick a random possible flower position, remove it from the table possibleFlowerPositions (so you won't pick it again), and then the removed element gets stored in the position variable.

Re: assigning table.remove to a variable then using it to print a number

Posted: Sat Jul 22, 2017 10:37 am
by zorg
Also, the following code

Code: Select all

local possibleFlowerPositions = {}
for y = 1, 14 do
 for x = 1, 19 do
  table.insert(possibleFlowerPositions, {x = x, y = y})
 end
end
is equivalent to this:

Code: Select all

local possibleFlowerPositions = {}
for y = 1, 14 do
 for x = 1, 19 do
  possibleFlowerPositions[#possibleFlowerPositions+1] = {['x'] = x, ['y'] = y}
 end
end
If that part was also unclear, since you had things like x=x and y=y in there, the characters on the left side of the = symbol were syntax sugar-ed string keys, as you can see from the second code block.