units here is a global variable of script. If the first line of that snip was "units = units or {}", it would recall the existing table instead of making a new one on next unchanged script call. Script global variables are stored in dfhack.internal.scripts on per-script basis, though you're generally preferred to use dfhack.script-environment rather than accessing that. (Not to be confused with predefined variables global to all scripts, such as COLOR_YELLOW).
i and unit are local to the for-loop, only have values in the for-loop, and are given those values by the pairs function. pairs function is an iterator function* that will take a list and keep giving new values to i and unit from said list, until it has run through entire table, not necessarily in order.
units.n is equivalent to units['n'].
units[n] is equivalent to units[whatever n is set to].
i.e.
local n, units = 1, {}
units[n] = "a"
units.n = "b"
units['1'] = "c"
printall(units)
will output
1 = a
n = b
1 = c
Secondary note on ipairs vs pairs:
Note that here ipairs, which only looks at numerically indiced keys, will appear really similar to pairs, since all keys are set on numbers 0 .. n - indeed, they return the same total count. And ipairs can be great for keeping your data constrained when passing it from function to function. But when it comes to lua tables, it'll count from 1 rather than df's 0, so if you did, say,
:lua unitlist = {} for i,v in pairs(df.global.world.units.active) do unitlist[i]=v end
then
:lua local count=0 for i,v in ipairs(unitlist) do count = count +1 end print(count)
Will print out 1 less than pairs would, even though directly accessing df.global.world.units.active with pairs and ipairs will give the same count.
* Meaning it returns another function, state variable for keeping track and first variable, and the for loop will keep calling the returned function with the two variables it returned until the first variable is nil. You can write your own iterators, but I don't expect you to need to.
PS:
http://www.lua.org/pil/contents.html and
http://lua-users.org/wiki/ can be helpful for learning lua in general, though that will make you miss functions like dfhack.timeout(numberOfticks, function).