AlexMili
AlexMili

Reputation: 41

implementing torch's __len__ meta function

In our torch-dataframe project we're trying to implement __len__ meta function as follows :

MyClass.__len__ = argcheck{
    {name="self", type="MyClass"},
    {name="other", type="MyClass"},
    call=function(self, other)
    return self.n_rows
end}

This works in Lua 5.2 and 5.3 but for Lua 5.1, luajit 2.0 and 2.1 the returned variable is not the actual row number but 0. The sense is that it returns a new instance of MyClass but it's hard to understand why. There is a note about __len changing here but that's the best doc hint we've managed to locate so far.

A little surprising is the need for two arguments. When argcheck is provided with a single argument version:

MyClass.__len__ = argcheck{
   {name = "self", type = "MyClass"},
   call=function(self)
   return self.n_rows
end}

it throws:

[string "argcheck"]:28: 
Arguments:

({
   self = MyClass  -- 
})


Got: MyClass, MyClass

We currently rely on the argcheck overload operator for handling this:

MyClass.__len__ = argcheck{
    {name="self", type="MyClass"},
    {name="other", type="MyClass"},
    call=function(self, other)
    return self.n_rows
end}

MyClass.__len__ = argcheck{
    overload=MyClass.__len__,
    {name="self", type="MyClass"},
    call=function(self)
    return self.n_rows
end}

For more details here is the full class and the travis report :

Test case

Here's a full test-case that works as expected in 5.2 and 5.3 that perhaps illustrates the problem in a more concise way that the full package:

require 'torch'
local argcheck = require "argcheck"

local MyClass = torch.class("MyClass")

function MyClass:init()
    self.n_rows = 0
end

MyClass.__len__ = argcheck{
    {name = "self", type = "MyClass"},
    {name = "other", type = "MyClass"},
    call=function(self, other)
    print(self.n_rows)
    print(other.n_rows)
    return(self.n_rows)
end}

local obj = MyClass.new()
obj.n_rows = 1
local n = #obj
print(n)

This prints as expected:

1
1
1

Upvotes: 1

Views: 94

Answers (1)

Max Gordon
Max Gordon

Reputation: 5467

The issue is related to this SO question. There simply is no support for it in 5.1:

__len on tables is scheduled to be supported in 5.2. See LuaFiveTwo.

Upvotes: 0

Related Questions