一 Lua基本语法:
1 变量:
1. 变量默认都是全局变量(一个文件中的变量所有的文件都可以访问),加上local变为局部变量,仅仅该文件可访问。
2. 变量类型:nil、Boolean、string、Number和table 。 在Lua中使用变量不需要提前声明,变量的类型决定于用户赋值的类型 。 可以使用 type()函数判断变量的类型。
3. 给一个变量赋值为nil,表示释放该变量。Boolean跟其他语言一样,只有true和false两种值。Number是双精度浮点数,Lua中没有整数类型。
4. String可以用单引号或者双引号来初始化,连接使用两个字符串使用..
5. 未定义的 变量值为nil,不是错误。只有nil 和false为假,0 和 '' 为真
2 注释:
用 “- - ”来标记该行的注释,使用“- - [ [” 和 “ - - ] ] ”之间括起来的部分进行块注释
3 运算符:
Lua中支持的算术运算符有:+、-、*、/,支持的关系运算符有:==、~=(不等于)、<、>、<=、>=;支持的逻辑运算符有:and、or、not,并且都是左短路
4 控制语句:
1. if,else 中间多了then
2. 代码块必须要有end结尾
3. for循环中:begin,end,step的结构,包括begin和end
-- Blocks are denoted with keywords like do/end:
while num < 50 do
num = num + 1 -- No ++ or += type operators.
end
-- If clauses:
if s ~= 'walternate' then -- ~= is not equals.
io.write('not over 40\n') -- Defaults to stdout.
else
local line = io.read() -- Reads next stdin line.
print('Winter is coming, ' .. line)
end
karlSum = 0
for i = 1, 100 do -- The range includes both ends.
karlSum = karlSum + i
end
-- Use "100, 1, -1" as the range to count down:
fredSum = 0
for j = 100, 1, -1 do fredSum = fredSum + j end
-- In general, the range is begin, end[, step].
repeat
print('the way of the future')
num = num - 1
until num == 0
5 函数
函数是以function关键字开始,然后是函数名称,参数列表,最后以end关键字表示函数结束。需要注意的是,函数中的参数是局部变量,如果参数列表中存在(…)时,Lua内部将创建一个类型为table的局部变量arg,用来保存所有调用时传递的参数以及参数的个数(arg.n) 。
function fib(n)
if n < 2 then return 1 end
return fib(n - 2) + fib(n - 1)
end
-- Closures and anonymous functions are ok:
function adder(x)
-- The returned function is created when adder is
-- called, and remembers the value of x:
return function (y) return x + y end
end
a1 = adder(9)
a2 = adder(36)
print(a1(16)) --> 25
print(a2(64)) --> 100
-- Unmatched receivers are nil;
-- unmatched senders are discarded.
function bar(a, b, c)
print(a, b, c)
return 4, 8, 15, 16, 23, 42
end
x, y = bar('zaphod')
--> prints "zaphod nil nil"
-- Now x = 4, y = 8, values 15..42 are discarded.
-- Functions are first-class, may be local/global.
-- These are the same:
function f(x) return x * x end
f = function (x) return x * x end
-- And so are these:
local function g(x) return math.sin(x) end
local g; g = function (x) return math.sin(x) end
-- the 'local g' decl makes g-self-references ok.
-- Trig funcs work in radians, by the way.
6 表
table可以作为列表或者字典使用,使用非nil的值作为key,通常是字符或者数字
t = {key1 = 'value1', key2 = false}
print(t.key1) -- Prints 'value1'.
t.newKey = {} -- Adds a new key/value pair.
t.key2 = nil -- Removes key2 from the table.
-- Key matching is basically by value for numbers and strings, but by identity for tables.
u = {['@!#'] = 'qbert', [{}] = 1729, [6.28] = 'tau'}
a = u['@!#'] -- Now a = 'qbert'.
b = u[{}] -- We might expect 1729, but it's nil:
-- b = nil since the lookup fails because the key we used is not the same object as the one used to store the original value.
for key, val in pairs(u) do -- Table iteration.
print(key, val)
end
-- _G is a special table of all globals.
print(_G['_G'] == _G) -- Prints 'true'.
-- List literals implicitly set up int keys:
v = {'value1', 'value2', 1.21, 'gigawatts'}
for i = 1, #v do -- #v is the size of v for lists.
print(v[i])
end
-- A 'list' is not a real type. v is just a table
7 类:
通过table实现类的功能
-- Classes aren't built in; there are different ways
-- to make them using tables and metatables.
Dog = {} -- 1.
function Dog:new() -- 2.
newObj = {sound = 'woof'} -- 3.
self.__index = self -- 4.
return setmetatable(newObj, self) -- 5.
end
function Dog:makeSound() -- 6.
print('I say ' .. self.sound)
end
mrDog = Dog:new() -- 7.
mrDog:makeSound() -- 'I say woof' -- 8.
-- 1. Dog acts like a class; it's really a table.
-- 2. function tablename:fn(...) is the same as
-- function tablename.fn(self, ...)
-- The : just adds a first arg called self.
-- Read 7 & 8 below for how self gets its value.
-- 3. newObj will be an instance of class Dog.
-- 4. self = the class being instantiated. Often
-- self = Dog, but inheritance can change it.
-- newObj gets self's functions when we set both
-- newObj's metatable and self's __index to self.
-- 5. Reminder: setmetatable returns its first arg.
-- 6. The : works as in 2, but this time we expect
-- self to be an instance instead of a class.
-- 7. Same as Dog.new(Dog), so self = Dog in new().
-- 8. Same as mrDog.makeSound(mrDog); self = mrDog.
-- Inheritance example:
LoudDog = Dog:new() -- 1.
function LoudDog:makeSound()
s = self.sound .. ' ' -- 2.
print(s .. s .. s)
end
seymour = LoudDog:new() -- 3.
seymour:makeSound() -- 'woof woof woof' -- 4.
-- 1. LoudDog gets Dog's methods and variables.
-- 2. self has a 'sound' key from new(), see 3.
-- 3. Same as LoudDog.new(LoudDog), and converted to
-- Dog.new(LoudDog) as LoudDog has no 'new' key,
-- but does have __index = Dog on its metatable.
-- Result: seymour's metatable is LoudDog, and
-- LoudDog.__index = LoudDog. So seymour.key will
-- = seymour.key, LoudDog.key, Dog.key, whichever
-- table is the first with the given key.
-- 4. The 'makeSound' key is found in LoudDog; this
-- is the same as LoudDog.makeSound(seymour).
-- If needed, a subclass's new() is like the base's:
function LoudDog:new()
newObj = {}
-- set up newObj
self.__index = self
return setmetatable(newObj, self)
end
8 模块
- require文件会被缓存,所以一般最多只调用一次require;dofile 类似require方式,但是没有缓存,可以多次调用;loadfile只load文件而没有运行文件
- ‘:’和’.’的区别:’只要出现了”:”,对于调用就将自身作为第一个参数传入; 对于函数定义的话,就将传入的第一个参数作为self。obj.Wakeup(obj,1)和obj:Wakeup(1)是等价的。结果都是传入2个参数:obj和1 。
-- Suppose the file mod.lua looks like this:
local M = {}
local function sayMyName()
print('Hrunkner')
end
function M.sayHello()
print('Why hello there')
sayMyName()
end
return M
-- Another file can use mod.lua's functionality:
local mod = require('mod') -- Run the file mod.lua.
-- require is the standard way to include modules.
-- require acts like: (if not cached; see below)
local mod = (function ()
<contents of mod.lua>
end)()
-- It's like mod.lua is a function body, so that
-- locals inside mod.lua are invisible outside it.
-- This works because mod here = M in mod.lua:
mod.sayHello() -- Says hello to Hrunkner.
-- This is wrong; sayMyName only exists in mod.lua:
mod.sayMyName() -- error
-- require's return values are cached so a file is
-- run at most once, even when require'd many times.
-- Suppose mod2.lua contains "print('Hi!')".
local a = require('mod2') -- Prints Hi!
local b = require('mod2') -- Doesn't print; a=b.
-- dofile is like require without caching:
dofile('mod2.lua') --> Hi!
dofile('mod2.lua') --> Hi! (runs it again)
-- loadfile loads a lua file but doesn't run it yet.
f = loadfile('mod2.lua') -- Call f() to run it.
-- loadstring is loadfile for strings.
g = loadstring('print(343)') -- Returns a function.
g() -- Prints out 343; nothing printed before now.
参考资料:
http://tylerneylon.com/a/learn-lua/
二 Tensor:
1 表示 Tensor/rand/zeros/ones
a = torch.Tensor(2,3)
b = torch.zeros(2,2)
t = torch.ones(2,2)
c = torch.rand(2,2)
2 转换:floor/ceil/int/long/zero/fill
a = torch.rand(2,2)
b = a:ceil():int():zero()
3 查询尺寸:size/nDimension/nElement
s = torch.LongStorage(6)
s[1] = 4; s[2] = 5; s[3] = 6; s[4] = 2; s[5] = 7; s[6] = 3;
x = torch.Tensor(s)
> x:nDimension()
6
> x:size()
4
5
6
2
7
3
[torch.LongStorage of size 6]
> x:nElement()
5040
4 运算:equal/add/mul/cmul/
四种表达形式:
y = torch.add(a, b) returns a new Tensor.
torch.add(y, a, b) puts a + b in y.
a:add(b) accumulates all elements of b into a.
y:add(a, b) puts a + b in y。
add 操作时,元素的数目必须match,但是size可以不match
mul是tensor与数字的乘法,而cmul则是tensor之间的乘法
--Returns true if the dimensions and values of tensor1 and tensor2 are exactly the same.
a = torch.zeros(1,2)
b = torch.ones(1,2)
> a:equal(b)
false
> x = torch.Tensor(2, 2):fill(2)
> y = torch.Tensor(4):fill(3)
> x:add(y)
> x
5 5
5 5
[torch.DoubleTensor of size 2x2]
x:add(2, y) --multiply y with 2
> x
11 11
11 11
[torch.DoubleTensor of size 2x2]
> x:mul(2)
22 22
22 22
>x:cmul(y)
66 66
66 66
5 截取:select/narrow/sub/{}
- select是直接提取某一维;narrow是取出某一维来截取一部分; sub就是取出一块,是对取出的所有维进行裁剪。
语法格式:语法: select(dim, index); narrow(dim, index, num); sub(dim1s, dim1e, dim2s, dim2e,…) - 用”{ }和[]”来提取
[ {dim1 , dim2, …} ]来获取某些维度。类似select
[ { {dim1s, dim1e}, {dim2s, dim2e},… } ] 类似sub
[ { dim1, {dim2s, dim2e},… }]相当于narrow
x = torch.Tensor(3,4)
i = 0
x:apply(function()i = i+1 return i end)
--[[
x 为
1 2 3 4
5 6 7 8
9 10 11 12
]]
selected = x:select(1,2) --第一维的第二个。就是第二行。相当于x[2]
narrowed = x:narrow(2,1,2)
--[[
th> narrowed
1 2
5 6
9 10
]]
subbed = x:sub(1,3,2,3)
--[[ 一维到3为止,二维也到3为止。
th> subbed
2 3
6 7
10 11
]]
x[{1,2}] -- 2
x[{1,{1,2}}] --1 2
待补充
参考:
https://github.com/torch/torch7/blob/master/doc/tensor.md
http://blog.csdn.net/hungryof/article/details/51802829