In python, we use for i, _ in enumerate(wx):
where wx
is a row matrix or table.
How can we use this in lua/torch. Any enumerate function?
1 Answers
In Lua, you have pairs
and ipairs
:
pairs (t)
If
t
has a metamethod__pairs
, calls it witht
as argument and returns the first three results from the call.Otherwise, returns three values: the
next
function, the tablet
, andnil
, so that the constructionfor k,v in pairs(t) do body end
will iterate over all key–value pairs of table
t
.
You can also use next
, for creating your own custom enumeration:
next (table [, index])
Allows a program to traverse all fields of a table. Its first argument is a table and its second argument is an index in this table. next returns the next index of the table and its associated value. When called with
nil
as its second argument,next
returns an initial index and its associated value. When called with the last index, or withnil
in an empty table,next
returns nil. If the second argument is absent, then it is interpreted as nil. In particular, you can usenext(t)
to check whether a table is empty.The order in which the indices are enumerated is not specified, even for numeric indices. (To traverse a table in numerical order, use a numerical for.)
The behavior of
next
is undefined if, during the traversal, you assign any value to a non-existent field in the table. You may however modify existing fields. In particular, you may clear existing fields.

- 78,589
- 36
- 144
- 183
-
@Sibi It'd be `a= { 1, 2, 3 }` – hjpotter92 Jun 03 '16 at 07:14
-
In Lua if you use table then it works `a={1,2,3} for i,v in ipairs(a) do print(i,v) end` – moteus Jun 03 '16 at 07:15
-
Why isn't it working when I declare `a=torch.rand(4,5)`? I need it to work for these types of `a` – Sibi Jun 03 '16 at 07:20
-
`a` is not a table but a 2D tensor so use [`apply`](https://github.com/torch/torch7/blob/master/doc/tensor.md#applying-a-function-to-a-tensor) or convert it with `a:totable()`. See also: http://stackoverflow.com/questions/34123291/torch-apply-function-over-dimension – deltheil Jun 03 '16 at 07:56