I am trying to find something analogous to the class in lua. In python, I would do:
a = {}
type(a)
>>>> dict
So I have the object vocab in lua. When I print the object, I get:
print(vocab)
>>> {
3 : 20
o : 72
m : 70
d : 61
( : 9
}
how can I get lua to spit the object, something analogous to the type() in python? - which will give you the class of the object
There are 8 types in Lua
: nil, boolean, number, string, function, thread, table and userdata. You can find out which of these basic types your object belongs to using built-in type()
function:
type('Hello world') == 'string'
type(3.14) == 'number'
type(true) == 'boolean'
type(nil) == 'nil'
type(print) == 'function'
type(coroutine.create(function() end)) == 'thread'
type({}) == 'table'
type(torch.Tensor()) == 'userdata'
Note that the type of torch.Tensor
is userdata. That makes sense since torch
library is written in C.
The type userdata is provided to allow arbitrary C data to be stored in Lua variables. A userdata value is a pointer to a block of raw memory. Userdata has no predefined operations in Lua, except assignment and identity test.
The metatable for the userdata is put in the registry, and the __index field points to the table of methods so that the object:method() syntax will work.
So, dealing with a userdata object, we do not know what it is but have a list of its methods and can invoke them.
It would be great if custom objects had some mechanism (a method or something) to see their custom types. And guess what? Torch objects have one:
t = torch.Tensor()
type(t) == 'userdata' # Because the class was written in C
torch.type(t) == 'torch.DoubleTensor'
# or
t:type() == 'torch.DoubleTensor'
Speaking of Torch
. It has its own object system emulator, and you are free to create some torch classes yourself and check their types the same way. For Lua
, however, such classes/objects are nothing more than ordinary tables.
local A = torch.class('ClassA')
function A:__init(val)
self.val = val
end
local B, parent = torch.class('ClassB', 'ClassA')
function B:__init(val)
parent.__init(self, val)
end
b = ClassB(5)
type(b) == 'table' # Because the class was written in Lua
torch.type(b) == 'ClassB'
b:type() # exception; Custom Torch classes have no :type() method by defauld