1

I am new to Lua and I am trying to learn it. Recently I came across below line of code which I believe is extracting some value from the table.

local context = context_proto[{{1, batch_size}, {1, source_l*imgH}}]

I have not seen this particular approach to read the table before. I would highly appreciate if anyone can help me understand what exactly above code is doing.

1
  • 1
    This means getmetatable(context_proto).__index will be called with {{1, batch_size}, {1, source_l*imgH}} as second parameter, and the result of this call will be assigned to context Commented Feb 27, 2018 at 19:18

2 Answers 2

1

The code you see here doesn't make too much sense in native Lua without further code. It is commonly used in Torch. I found your snippet in a torch related script online. So I guess that's a valid guess.

I'm not very experienced with Torch, but from what I see in the documentation this will give you a sub-tensor of context_proto. row 1-batchSize and col source_l * imgH.

I think it is called slicing and it is covered in the following demo/tutorial: https://github.com/torch/demos/blob/master/tensors/slicing.lua

print 'more complex slicing can be done using the [{}] operator'
print 'this operator lets you specify one list/number per dimension'
print 'for example, t2 is a 2-dimensional tensor, therefore'
print 'we should pass 2 lists/numbers to the [{}] operator:'
print ''

t2_slice1 = t2[{ {},2 }]
t2_slice2 = t2[{ 2,{} }]      -- equivalent to t2[2]
t2_slice3 = t2[{ {2},{} }]
t2_slice4 = t2[{ {1,3},{3,4} }]
t2_slice5 = t2[{ {3},{4} }]
t2_slice6 = t2[{ 3,4 }]
...

Please refer to the torch documentation for more details.

https://github.com/torch/torch7/blob/master/doc/tensor.md#tensor--dim1dim2--or--dim1sdim1e-dim2sdim2e-

Sign up to request clarification or add additional context in comments.

Comments

1

From the Lua Documentation:

The type table implements associative arrays, that is, arrays that can be indexed not only with numbers, but with any Lua value except nil and NaN.

That code is using a table as an index into another table. It might be clearer if it were written as follows:

local contextIndex = {{1, batch_size}, {1, source_l*imgH}}
local context = context_proto[contextIndex]

1 Comment

I think Egor's comment is more useful, as while this answer is technically correct, it's incomplete, because the value returned will always be nil without using __index metamethod (as the table value used as index is constructed on the fly and can't match anything).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.