Q:

Loop over first n elements of Lua table

I have a for loop in which I'm doing some action that I want to do only max n times.  So far I have done this by means of a local variable which I increment in the loop, and each time check to see if it exceeded the counter limit.  If it does, I break out of the loop. 
for _,u in GetAllUnits() do
        if not u:IsInCategory("STRUCTURE") and not u:IsInCategory("COMMAND") then
                NameUnit(u)
                nameCount = nameCount + 1
                if nameCount >= maxUnitNames then break end
        end
end

I'm very new to Lua and wonder if there is a better way to do this.  It's important that I don't end up creating a copy of the table or some other expensive operation. 
Note that the _ contains the ID of the unit, so this cannot be used instead of the counter. 

A:

If you are concerned about the imperative nature of that piece of code, you can always use the usual functional approaches:
local function notStructureNotCommand( _, u )
  return not u:IsInCategory( "STRUCTURE" ) and
         not u:IsInCategory( "COMMAND" )
end

for _,u in take( maxUnitNames, filter( notStructureNotCommand, GetAllUnits() ) ) do
  NameUnit( u )
end

You can do functional programming quite nicely in Lua, but you'll have to look for the usual helper functions like map, filter, etc.  in an external library.  There are a lot of implementations of those functions in the LuaRocks repository, but in your case you have to make sure that you get a version that works on iterators instead of (or in addtion to) tables.  If you don't find anything suitable, you can use the functions below:
local filter
do
  local function filter_helper( pred, f, s, var_1, ... )
    if var_1 ~= nil then
      if pred( var_1, ... ) then
        return var_1, ...
      else
        return filter_helper( pred, f, s, f( s, var_1 ) )
      end
    end
  end

  function filter( pred, f, s, var )
    return function( st, v )
      return filter_helper( pred, f, st, f( st, v ) )
    end, s, var
  end
end

local function take( n, f, s, var )
  return function( st, v )
    if n > 0 then
      n = n - 1
      return f( st, v )
    end
  end, s, var
end

