lua-users home
lua-l archive

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


On Wed, Apr 19, 2000 at 10:26:43AM -0300, Roberto Ierusalimschy wrote:
> > eg. "for" keyword instead of a function in Lua.
> 
> We forgot to tell: Lua will have a "for"! (next week)

What will the style of the for be?

One of things which I like most about Python is the simple list based
"for". It's responsible for preventing lots of bugs IMO. However, I
noticed a snafu with doing this kind of thing in Lua, namely that
there dosn't seem to be a "next" tag method.

-- For example, given a Python-esq looping structure like:

  a = { 5, 6, 2 };

  for num in a do
    print num;
  end

-- you could have python style number loops based on a table/list, 
-- if you had a "next" tag.

  function range_next(table,curindex)
    if curindex == nil then
      return table['start'];
    end

    if curindex >= table['max'] then
      return nil;
    end
      
    return (curindex + 1);
  end

  range_tag = newtag()
  settagmethod(range_tag, "next", range_next)

  function range(max)
    loop_parms = { start = 0, max = max};
    settag(loop_parms, range_tag);
    return loop_parms;
  end

  for num in range(4) do
    print num
  end

---------------------------------------
-- I'm not as fond of the C style number loops
-- because they are so prone to errors:

  a = { 1, 2, 3 }

  len_a = length(a)

  for (x=0; x=x+1; x< len_a) do
    print num
  end

-- although at least you can do this:

  a = {1, 2, 3}

  for (num=next(a);num=next(a,x); num!=nil) do
    print num
  end

-- With only basic number style loops, iteration will
-- be somewhat strange IMO. Witness the example below:
 
  a = { 5, 6, 2 ; val = "this will cause weird behavior" }

  len_a = length(a) -- 4

  for num = 1 to length(a) do
    print a[num]
  end

  -- outputs: 5, 6, 2, nil

-- 
David Jeske (N9LCA) + http://www.chat.net/~jeske/ + jeske@chat.net