Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enumerate function in lua/torch

Tags:

python

torch

lua

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?

like image 755
Sibi Avatar asked Feb 23 '26 08:02

Sibi


1 Answers

In Lua, you have pairs and ipairs:

pairs (t)

If t has a metamethod __pairs, calls it with t as argument and returns the first three results from the call.

Otherwise, returns three values: the next function, the table t, and nil, so that the construction

for 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 with nil in an empty table, next returns nil. If the second argument is absent, then it is interpreted as nil. In particular, you can use next(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.

like image 79
hjpotter92 Avatar answered Feb 25 '26 22:02

hjpotter92