lua-users home
lua-l archive

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


On Sat, May 22, 2010 3:49 pm, Klaus Ripke wrote:
> now that everybody hates to write
>
> for i = 1, #t do
> 	v = t[i] -- optional: if nil == v then break end
> 	...
> end

Note that the trivial implementation isn't even 100% compatible with the
current ipairs. If you forget the difference, you might end up with bugs
in your software after you clean out the ipairs calls from it. For
example:

print("With ipairs");
a = { 1, 2, 3 };

math.randomseed(1234);
for i,v in ipairs(a) do
	if math.random() > 0.1 then
		table.insert(a, i);
	end

	print(i,v); -- Prints out 36 pairs of values
end

print("Without ipairs");
b = { 1, 2, 3 };

math.randomseed(1234);
for i = 1, #b do
	if math.random() > 0.1 then
		table.insert(b, i);
	end

	print(i, b[i]);  -- Prints out 3 pairs of values
end

Ipairs allows you to add items to the list. If you evaluate the length of
the list in a numeric loop, you can't add new items to the list within the
loop and expect them to be looped through. Similarly, deleting items from
a table within the loop will behave differently with ipairs and a numeric
loop using #table.

I think a method of traversing a table in numerical order is common enough
and useful enough so that it deserves some "syntactic sugar". My colleague
here at work isn't very experienced with Lua, but when I showed him code
with ipairs and without, he felt that the version with ipairs was more
easily understood and cleaner.

>From an optimization point of view, I would think that it would make sense
to have easily optimized syntactical structures for ipairs and pairs. If
Lua tables are stores with an array component, traversing the array part
can be heavily optimized.

There is room to expand the for k,v in x do expression so that when the
first value in x is not a function, it would for instance iterated over a
table or hash. In the current implementation, the first item has to be a
function.

Some very rough ideas:

t = { 1,2,3 }

for k,v in t do    -> could be equivalent to for k,v in pairs(t) do
for k,v in 1,t do -> could be equivalent to for k,v in ipairs(t) do
for k,v in 0,t do -> could do the same, but start from zero instead of 1.

The type of the first value after in would determine how the for loop
would behave. A function would make it use the iterator function, a table
would make it replicate the behavior of next and the an integer would make
it work very much like ipairs (with the value 1 replicating ipairs
exactly).

Sincerely,

  Juri Munkki
  jmunkki@portalify.com

P.S. Stil