Ale*_*ich 1 python lua class torch
我试图在lua中找到类似于类的东西.在python中,我会这样做:
a = {}
type(a)
>>>> dict
Run Code Online (Sandbox Code Playgroud)
所以我在lua中有对象词汇.当我打印对象时,我得到:
print(vocab)
>>> {
3 : 20
o : 72
m : 70
d : 61
( : 9
}
Run Code Online (Sandbox Code Playgroud)
我如何让lua吐出对象,类似于python中的type()? - 它将为您提供对象的类
有8种类型Lua:nil,boolean,number,string,function,thread,table和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'
Run Code Online (Sandbox Code Playgroud)
请注意,类型torch.Tensor是userdata.这有道理,因为torch库是用C语言编写的.
提供类型userdata以允许任意C数据存储在Lua变量中.userdata值是指向原始内存块的指针.除了赋值和身份测试之外,Userdata在Lua中没有预定义的操作.
userdata的metatable放在注册表中,__ index字段指向方法表,以便object:method()语法可以工作.
因此,处理userdata对象时,我们不知道它是什么,但有一个方法列表并可以调用它们.
如果自定义对象有一些机制(方法或某种东西)来查看它们的自定义类型,那将会很棒.你猜怎么着?火炬对象有一个:
t = torch.Tensor()
type(t) == 'userdata' # Because the class was written in C
torch.type(t) == 'torch.DoubleTensor'
# or
t:type() == 'torch.DoubleTensor'
Run Code Online (Sandbox Code Playgroud)
说到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
Run Code Online (Sandbox Code Playgroud)