Thread: lua language
View Single Post
12-02-14, 11:13 AM   #5
sirann
A Flamescale Wyrmkin
Join Date: Mar 2007
Posts: 142
First I had to clean up your code lol:
Lua Code:
  1. gridWidth = 9
  2. gridHeight = 14
  3. grid = {}
  4.  
  5. for i=1, gridWidth, 1 do   
  6.     grid[i] = {}
  7. end
  8.  
  9. function tappedRect(event)
  10.     if event.target.ship then  
  11.         event.target.ship = true   
  12.         event.target:setFillColor(255, 0, 0)   
  13.     else
  14.         event.target.ship = false
  15.         event.target:setFillColor(0,255, 0)
  16.     end
  17. end
  18.  
  19. squareWidth = 25   
  20. squareHeight = 25  
  21. gap = 5
  22.  
  23. for i =1, gridWidth, 1 do  
  24.     for j =1, gridHeight, 1 do
  25.         grid[i][j] = display.newRect((gap* i) + (i*squareWidth) , (gap* j) + (j* squareHeight), squareWidth, squareHeight)
  26.     end
  27. end
  28.  
  29. for i =1, gridWidth, 1 do  
  30.     for j =1, gridHeight, 1 do
  31.         grid[i][j].ship = false
  32.         grid[i][j]:addEventListener("tap", tappedRect) 
  33.     end
  34. end
  35.  
  36. function addShip(shipSize)
  37.     x = math.random(1, gridWidth)
  38.     y = math.random(1, gridHeight)
  39.     for i = 1, shipSize-1, 1 do
  40.         if grid[x-1][y].ship then
  41.             grid[x-i][y]:setFillColor(255,0,0)
  42.         end
  43.     end
  44. end
  45.  
  46. addShip(2)

Then I saw
Lua Code:
  1. for i=1, gridWidth, 1 do    
  2.     grid[i] = {}
  3. end
which I'm pretty sure creates nested tables at keys of 1-9-1, which is a bit redundant. Should just be
Lua Code:
  1. for i = 1, gridWidth do

Then you try to perform an if check that will always be false as you never declared the event table:
Lua Code:
  1. if event.target.ship then  
  2.         event.target.ship = true    
  3.         event.target:setFillColor(255, 0, 0)    
  4.     else
  5.         event.target.ship = false
  6.         event.target:setFillColor(0,255, 0)
  7.     end

More redundancy of for loops over writing table values
Lua Code:
  1. for i =1, gridWidth, 1 do  
  2.     for j =1, gridHeight, 1 do

So, quite a bit of work (more than I posted) needs to be done to make this functional!