我试图找到类似于 lua 中的类的东西。在 python 中,我会这样做:
a = {}
type(a)
>>>> dict
所以我在 lua 中有对象词汇表。当我打印对象时,我得到:
print(vocab)
>>> {
3 : 20
o : 72
m : 70
d : 61
( : 9
}
如何让 lua 吐出对象,类似于 python 中的 type()? - 这将为您提供对象的类别
请您参考如下方法:
There are 8 types in Lua : nil, boolean, number, string, function, thread, table and userdata.您可以使用内置的 type() 函数找出您的对象属于这些基本类型中的哪些:
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'
请注意,torch.Tensor 的类型是 userdata。这是有道理的,因为 torch 库是用 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.
因此,处理用户数据对象时,我们不知道它是什么,但有它的方法列表并且可以调用它们。
如果自定义对象有某种机制(方法或其他东西)来查看它们的自定义类型,那就太好了。你猜怎么着? torch 对象有一个:
t = torch.Tensor()
type(t) == 'userdata' # Because the class was written in C
torch.type(t) == 'torch.DoubleTensor'
# or
t:type() == 'torch.DoubleTensor'
说到 Torch。它有自己的对象系统模拟器,你可以自由地自己创建一些 torch 类并以相同的方式检查它们的类型。然而,对于Lua,这样的类/对象只不过是普通的表。
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
