lua-users home
lua-l archive

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



On 28-Sep-06, at 7:56 PM, Wesley Smith wrote:

I'm trying to "clear" an array after a loop is run and reuse it again
on the next iteration.  By "clear" I mean that I wat #array to be 0.

So, if I have:

array = {}

--add stuff to array in loop
array[#array+1] = stuff

--end loop

--clear array
array[1] = nil
print(#array)

What I'm getting from the print statement is the length of the array
after the loop ended, not the expected 0.  Is this correct?  I don't
see why this wouldn't work.

# is not well-defined for tables unless their integer keys range from 1 to k, for some k. If a key is missing (i.e. it's associated value is nil), # may or may not notice it.

While you could loop over the table to clear it, you are probably better off just throwing the table away and using a new one for the next iteration. This would definitely be the case if "stuff" were something which required allocation, like another table.

If "stuff" is simple enough that you don't need to worry about about garbage collecting it (numbers, for example), then just keep your own index into the table and use that:

do
  -- initialization
  local array = {}

  -- start iteration
  while true do -- or some condition, or a for statement ...
    local top = 1

    -- inner loop
    for k, v in pairs(things) do -- or whatever
      -- add stuff to array in loop
      array[top] = stuff
      top = top + 1
    end

    -- mark the end of array (optional)
    array[top] = nil

    -- now you can iterate over the array reliably with ipairs
    for i, stuff in ipairs(array) do
      -- something
    end

    -- on to next iteration
    if done then break end
  end
end