I would recommend reading up on variable scoping. A simple tutorial specific to Lua can be found at:
iirc that tutorial does leave out one important thing, iterators are always local, for instance, in the line
"for k,v in pairs(test) do"
the variables k and v are automatically local to their iterative loop (you don't need to explicitly create them as local variables first).