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?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.