lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

On Mon, Nov 23, 2020 at 4:51 PM Sean Conner <> wrote:
It was thus said that the Great Egor Skriptunoff once stated:
> This loop is not pointless.
> It clears the cells which may contain "black" or "white" pieces from the
> previous game.
> The function initialize_game_field() is invoked on every game start.

  Given that any undefined key in a table returns nil, what's wrong with
this version of initialize_game_field()?

local function initialize_game_field()
   game_field = {} -- AN EMPTY TABLE
   for j = base_index, base_index + game_size - 1 do
      game_field[j] = "white"
   for j = base_index + 2*game_size, base_index + 3*game_size - 1 do
      game_field[j] = "black"

  Not only does the 0 case run as fast as the 1 case, but it runs a bit
faster overall as there's only two loops doing work, not three.

Because you are only seeing it as it runs on the initial startup, beginning with an empty table. Egor stated that, "It clears the cells which may contain "black" or "white" pieces from the previous game." In other words, this function will be run after *every* game, and after a game has been played, pieces may be in random positions, and the middle of the board needs to be explicitly set to nil to remove those pieces. In other words, the spaces being set to nil are not necessarily undefined, and may contain junk values that must be cleared before starting a new game. Only on the first run are those spaces guaranteed to be nil/undefined.