Kevin Bullaughey
Kevin Bullaughey

Reputation: 2576

How do I use torch's class system to create a custom class

I was attempting to follow the torch documentation for utility functions.

And I did the following:

Blah = torch.class('Blah')
function Blah:__init(); end
blah = Blah()

But I get the following error:

attempt to call global 'Blah' (a table value)

I was expecting the __init() function to somehow work via the __call metatable mechanism, but Blah doesn't even seem to have a metatable:

th> getmetatable(Blah) == nil
true

Maybe the documentation is out of date? But torch seems to be creating plenty of classes this way internally.

I just updated to the latest torch, so I know it's not my torch version is too old...

Thoughts?

Upvotes: 3

Views: 1572

Answers (2)

Geeocode
Geeocode

Reputation: 5797

1. You need:

local Blah = torch.class('Blah')

2. You need use:

do 
end 

lexical scoping, if you want to call class 'Blah' from the same module. But if you call it from an other module - as we mostly do with a class -, we don't need use do-end lexical scoping.

So if your module's purpose is just declaring a torch type class and then using it several time from other modules, you just need declare as local as above in the section 1. and you don't need (but you can) do-end lexical scoping.

Actually torch documentation remark:

-- for naming convenience

is a bit misleading here, I guess.

Upvotes: 0

smhx
smhx

Reputation: 2266

do
 local Blah = torch.class('Blah')
 function Blah:__init() end
end

blah = Blah()

Upvotes: 5

Related Questions