Guest User

Untitled

a guest
Jun 21st, 2015
260
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.17 KB | None | 0 0
  1. local dimensions = {}
  2. dimensions["width"] = 36
  3. dimensions["height"] = 20
  4.  
  5. local field = {}
  6.  
  7. for x = 1, dimensions["width"] do
  8. field[x] = {}
  9. for y = 1, dimensions["height"] do
  10. field[x][y] = 0
  11. end
  12. end
  13.  
  14. field[1][2] = 1
  15. field[2][2] = 1
  16. field[2][3] = 1
  17. field[3][3] = 1
  18.  
  19. function printField()
  20. for y = 1, dimensions["height"] do
  21. for x = 1, dimensions["width"] do
  22. if field[x][y] == 0 then
  23. write("-")
  24. else
  25. write("X")
  26. end
  27. end
  28. print()
  29. end
  30. end
  31.  
  32. function getCorrectCoords(x, y)
  33. if (x > dimensions["height"]) then
  34. x = 1
  35. elseif x < 1 then
  36. x = dimensions["width"]
  37. end
  38. if (y > dimensions["height"]) then
  39. y = 1
  40. elseif y < 1 then
  41. y = dimensions["height"]
  42. end
  43. res = {x, y}
  44. return res
  45. end
  46.  
  47. function countNeighbors(x, y)
  48. local neighbors = 0
  49. for why = 1, 3 do
  50. for ex = 1, 3 do
  51. local coords = getCorrectCoords((x-2)+ex, (y-2)+why)
  52. if field[coords[1]][coords[2]] == 1 then
  53. neighbors = neighbors + 1
  54. end
  55. end
  56. end
  57. if field[x][y] == 1 then
  58. neighbors = neighbors - 1
  59. end
  60. return neighbors
  61. end
  62.  
  63. function updateField()
  64. -- declares the field which will hold the new cell values
  65. local newfield = {} -- the problem persists even when newfield is a global variable
  66. -- fills newfield with 0's
  67. for x = 1, dimensions["width"] do
  68. newfield[x] = {}
  69. for y = 1, dimensions["height"] do
  70. newfield[x][y] = 0
  71. end
  72. end
  73. print(newfield[1][1]) -- this line executes, and throws no errors at all
  74. -- this block goes through cells, counts neighbors, and determines next state of cell
  75. for x = 1, dimensions["width"] do
  76. print(newfield[1][1]) -- past this point all newfield references throw errors
  77. for y = 1, dimensions["height"] do
  78. print(newfield[1][1]) -- this line executes, but as soon as it finishes it throws an error
  79. if (field[x][y] == 0) and (countNeighbors(x, y) == 3) then
  80. newfield[x][y] = 1
  81. elseif (field[x][y] == 1) and ((countNeighbors(x, y) == 3) or (countNeighbors(x, y) == 2)) then
  82. newfield[x][y] = 1
  83. else
  84. newfield = 0
  85. end
  86. end
  87. end
  88. field = newfield
  89. end
  90.  
  91. while true do
  92. sleep(0.5)
  93. term.clear()
  94. term.setCursorPos(1,1)
  95. updateField()
  96. printField()
  97. end
Advertisement
Add Comment
Please, Sign In to add comment