lua-users home
lua-l archive

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


It was thus said that the Great Jonathan Goble once stated:
> On Mon, Nov 23, 2020 at 4:51 PM Sean Conner <sean@conman.org> 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"
> >    end
> >    for j = base_index + 2*game_size, base_index + 3*game_size - 1 do
> >       game_field[j] = "black"
> >    end
> > end
> >
> >   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.

  Did you not see where I set game_field to an empty table prior to the
loops?  That pretty much wipes the entire board away, and it's initialized
with just the pieces.

  But here's an alternative---both 0 and 1 indecies run the same speed, it
doesn't involve nils, and may very well behave the same, depending upon how
one checks for nils:

local function initialize_game_field()
   for j = base_index, base_index + game_size - 1 do
      game_field[j] = "white"
   end
   for j = base_index + game_size, base_index + 2*game_size - 1 do
      game_field[j] = false
   end
   for j = base_index + 2*game_size, base_index + 3*game_size - 1 do
      game_field[j] = "black"
   end
end

  It seems many forget that both nil and false are falsey values in Lua. 
And from what I've heard from Roberto, false was added just for this
purpose---to store a nil-like value in a sequence (and then true was added
to make a true Boolean value).

  -spc