lua-users home
lua-l archive

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


Hi there,

A numeric for loop can be specified with a negative step using the
following syntax:

for idx = startidx,endidx,step do
    -- inner code
end

For example, printing the numbers 10 to 5:

for idx = 10,5,-1 do
    print(idx)
end

The loop you're using is a generic for loop, which makes an iterator
function responsible for the lifetime of a loop and the contents of
the loop variables.  In your case, luacom.pairs() is the iterator
function, and is responsible for assigning values to the loop
variables, index and cell.  Using a generic for loop to iterate a
collection from a given position, and in a certain direction, is
dependent on whether or not the iterator function supports such
actions.  I'm not sure if luacom.pairs() supports anything like this.

If luacom, and the Excel API for that matter, support a way of getting
cell contents via numeric indices, and you can get start and end
indices for iteration, then you might be able to write your loop as a
numeric for loop.  For example:

local startidx = -- get start index
local endidx = -- get end index
for idx = startidx, endidx, -1 do
    local cell = -- get cell at idx
    -- do stuff with the cell
end

This example assumes that both 'startidx' and 'endidx' are numbers,
and that 'startidx' is greater in value than 'endidx'.  It also
assumes that all cells in that range can be retrieved.  From what I
remember of Excel programming, which is quite little having programmed
a bit a while ago and in a different language, it was often finicky.

A side note: the above example uses the 'local' keyword is used to
make sure that the variables aren't declared as globals.

Now if you want the loop's inner code to be able to modify the index,
and have that change get recognized in subsequent iterations of the
loop, then you'll have to use a while loop, or a repeat/until loop.
In lua, both numeric and generic for loops seem to ignore changes to
loop variables made inside the loop.  For example, the following code
will print the integers 10 through 5 in order, without skipping any
numbers:

for idx = 10,5,-1 do
    print(idx)
    idx = idx - 2
end

I hope this helps!

--
David Ludwig
dludwig@pobox.com


On Sun, Dec 21, 2008 at 11:58 AM, Sean Farrow
<sean.farrow@seanfarrow.co.uk> wrote:
> I have the following code:
> excel = luacom.GetObject("Excel.Application")
> for index, cell in luacom.pairs(Excel.Columns(ActiveCell.Row).Cells) do
> --code.
> end
> Two queries:
> I need to traverse the loop from the current collumn, can I set index to this value?
> Also, How can I travese with a negative step, i.e to the previous collumn?
> Any help apreciated
> Sean.