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
type
from Python actually does.vocab
. The part that's not Lua is the table you create afterwards. Lua usesname = value,
syntax for table declarations; the table you show would yield a syntax error.print
statement. The obvious inference being that it's the same language as the rest. If you wanted to denote that it was the result of the Lua script, you should have made that more clear.