summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-rw-r--r--coffeescript.html.markdown42
-rw-r--r--go.html.markdown13
-rw-r--r--haskell.html.markdown2
-rw-r--r--lua.html.markdown2
-rw-r--r--pt-br/visualbasic-pt.html.markdown285
-rw-r--r--zh-cn/coffeescript-cn.html.markdown101
-rw-r--r--zh-cn/lua-cn.html.markdown413
7 files changed, 855 insertions, 3 deletions
diff --git a/coffeescript.html.markdown b/coffeescript.html.markdown
index c61cad67..86c875ba 100644
--- a/coffeescript.html.markdown
+++ b/coffeescript.html.markdown
@@ -2,9 +2,13 @@
language: coffeescript
contributors:
- ["Tenor Biel", "http://github.com/L8D"]
+ - ["Xavier Yao"], "http://github.com/xavieryao"]
filename: coffeescript.coffee
---
+CoffeeScript is a little language that compiles one-to-one into the equivalent JavaScript, and there is no interpretation at runtime.
+As one of the succeeders of JavaScript, CoffeeScript tries its best to output readable, pretty-printed and smooth-running JavaScript codes working well in every JavaScript runtime.
+
See also [the CoffeeScript website](http://coffeescript.org/), which has a complete tutorial on CoffeeScript.
``` coffeescript
@@ -30,6 +34,17 @@ number = -42 if opposite #=> if(opposite) { number = -42; }
# Functions:
square = (x) -> x * x #=> var square = function(x) { return x * x; }
+fill = (container, liquid = "coffee") ->
+ "Filling the #{container} with #{liquid}..."
+#=>var fill;
+#
+#fill = function(container, liquid) {
+# if (liquid == null) {
+# liquid = "coffee";
+# }
+# return "Filling the " + container + " with " + liquid + "...";
+#};
+
# Ranges:
list = [1..5] #=> var list = [1, 2, 3, 4, 5];
@@ -47,11 +62,36 @@ math =
# Splats:
race = (winner, runners...) ->
print winner, runners
+#=>race = function() {
+# var runners, winner;
+# winner = arguments[0], runners = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
+# return print(winner, runners);
+#};
# Existence:
alert "I knew it!" if elvis?
#=> if(typeof elvis !== "undefined" && elvis !== null) { alert("I knew it!"); }
# Array comprehensions:
-cubes = (math.cube num for num in list) #=> ...
+cubes = (math.cube num for num in list)
+#=>cubes = (function() {
+# var _i, _len, _results;
+# _results = [];
+# for (_i = 0, _len = list.length; _i < _len; _i++) {
+# num = list[_i];
+# _results.push(math.cube(num));
+# }
+# return _results;
+# })();
+
+foods = ['broccoli', 'spinach', 'chocolate']
+eat food for food in foods when food isnt 'chocolate'
+#=>foods = ['broccoli', 'spinach', 'chocolate'];
+#
+#for (_k = 0, _len2 = foods.length; _k < _len2; _k++) {
+# food = foods[_k];
+# if (food !== 'chocolate') {
+# eat(food);
+# }
+#}
```
diff --git a/go.html.markdown b/go.html.markdown
index d1a0ae34..a66e8c4b 100644
--- a/go.html.markdown
+++ b/go.html.markdown
@@ -7,6 +7,7 @@ contributors:
- ["Sonia Keys", "https://github.com/soniakeys"]
- ["Christopher Bess", "https://github.com/cbess"]
- ["Jesse Johnson", "https://github.com/holocronweaver"]
+ - ["Quint Guvernator", "https://github.com/qguv"]
---
Go was created out of the need to get work done. It's not the latest trend
@@ -180,9 +181,21 @@ func learnFlowControl() {
goto love
love:
+ learnDefer() // A quick detour to an important keyword.
learnInterfaces() // Good stuff coming up!
}
+
+
+func learnDefer() (ok bool) {
+ // deferred statements are executed just before the function returns.
+ defer fmt.Println("deferred statements execute in reverse (LIFO) order.")
+ defer fmt.Println("\nThis line is being printed first because")
+ // defer is commonly used to close a file, so the function closing the file
+ // stays close to the function opening the file
+ return true
+}
+
// Define Stringer as an interface type with one method, String.
type Stringer interface {
String() string
diff --git a/haskell.html.markdown b/haskell.html.markdown
index 341c013e..e0489710 100644
--- a/haskell.html.markdown
+++ b/haskell.html.markdown
@@ -303,7 +303,7 @@ Nothing -- of type `Maybe a` for any `a`
-- While IO can't be explained fully without explaining monads,
-- it is not hard to explain enough to get going.
--- When a Haskell program is executed, the function `main` is
+-- When a Haskell program is executed, `main` is
-- called. It must return a value of type `IO ()`. For example:
main :: IO ()
diff --git a/lua.html.markdown b/lua.html.markdown
index 27ce105b..bdd59999 100644
--- a/lua.html.markdown
+++ b/lua.html.markdown
@@ -321,7 +321,7 @@ seymour:makeSound() -- 'woof woof woof' -- 4.
-- 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
+-- LoudDog.__index = Dog. 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
diff --git a/pt-br/visualbasic-pt.html.markdown b/pt-br/visualbasic-pt.html.markdown
new file mode 100644
index 00000000..76cca567
--- /dev/null
+++ b/pt-br/visualbasic-pt.html.markdown
@@ -0,0 +1,285 @@
+---
+language: Visual Basic
+contributors:
+ - ["Brian Martin", "http://brianmartin.biz"]
+translators:
+ - ["AdrianoJP", "https://github.com/AdrianoJP"]
+lang: pt-br
+filename: learnvisualbasic-pt.vb
+---
+
+```vb
+Module Module1
+
+module Module1
+
+ Sub Main ()
+ ' Uma visão geral de console de aplicativos do Visual Basic antes de
+ ' mergulharmos mais profundamente na linguagem
+ ' Aspas simples começam comentários.
+ ' Para Navegar este tutorial dentro do compilador do Visual Basic,
+ ' eu criei um sistema de navegação.
+ ' Este sistema de navegação vai ser explicado conforme avançarmos no
+ ' tutorial, e você vai entender o que isso significa.
+ Console.Title = (" Saiba X em Y Minutes" )
+ Console.WriteLine ( "NAVEGAÇÃO" ) 'Mostrar
+ Console.ForegroundColor = ConsoleColor.Green
+ Console.WriteLine ("1. Saída Olá Mundo" )
+ Console.WriteLine ("2. Entrada Olá Mundo" )
+ Console.WriteLine ("3. Cálculando números inteiros " )
+ Console.WriteLine ("4. Calculando números decimais " )
+ Console.WriteLine ("5 . Calculadora de Trabalho " )
+ Console.WriteLine ("6. Usando Do While Loops " )
+ Console.WriteLine ("7. Usando Para While Loops " )
+ Console.WriteLine ("8 . Declarações condicionais " )
+ Console.WriteLine ("9. Selecione uma bebida" )
+ Console.WriteLine ("50 . About" )
+ Console.WriteLine ("Por favor, escolha um número da lista acima " )
+ Seleção Dim As String = Console.ReadLine
+ Select A seleção dos casos
+ Caso "1" 'Output HelloWorld
+ Console.clear () ' Limpa a aplicação e abre o sub privado
+ HelloWorldOutput () ' Nome Private Sub, Abre Private Sub
+ Caso "2" 'Olá entrada
+ Console.clear ( )
+ HelloWorldInput ( )
+ Caso de "3" 'Calculando Números Inteiros
+ Console.clear ( )
+ CalculatingWholeNumbers ( )
+ Caso "4" ' Números decimais Calculting
+ Console.clear ( )
+ CalculatingDecimalNumbers ( )
+ Caso "5" ' Calcculator Trabalho
+ Console.clear ( )
+ WorkingCalculator ( )
+ Caso "6" 'Usando Do While Loops
+ Console.clear ( )
+ UsingDoWhileLoops ( )
+ Caso de "7" 'Usando pois enquanto Loops
+ Console.clear ( )
+ UsingForLoops ( )
+ Caso "8" ' Instruções condicionais
+ Console.clear ( )
+ ConditionalStatement ( )
+ Caso "9" "Declaração If / Else
+ Console.clear ( )
+ IfElseStatement () ' Selecione uma bebida
+ Caso "50" 'Quem caixa de msg
+ Console.clear ( )
+ Console.Title = (" Saiba X em Y Minutos :: Quem " )
+ MsgBox (" Este tutorial é de Brian Martin ( @ BrianMartinn " )
+ Console.clear ( )
+ Main ()
+ Console.ReadLine ()
+
+ End Select
+ End Sub
+
+ ' Um - Eu estou usando números para ajudar com a navegação acima quando eu voltar
+ ' depois de construí-lo .
+
+ " Nós usamos subs privadas para separar diferentes seções do programa.
+ Private Sub HelloWorldOutput ()
+ ' Título de aplicativo do console
+ Console.Title = " Olá Mundo Ouput | Saiba X em Y Minutes"
+ 'Use Console.Write ("") ou Console.WriteLine ("") para imprimir saídas.
+ " Seguido por Console.Read () alternativamente Console.ReadLine ()
+ ' Console.ReadLine () imprime a saída para o console.
+ Console.WriteLine ( "Olá Mundo" )
+ Console.ReadLine ()
+ End Sub
+
+ ' Dois
+ Private Sub HelloWorldInput ()
+ Console.Title = " Olá Mundo YourName | Saiba X em Y Minutes"
+ ' Variáveis
+ 'Os dados inseridos por um usuário precisa ser armazenada .
+ ' As variáveis ​​também começar com um Dim e terminar com um Como VariableType .
+
+ ' Neste tutorial, nós queremos saber o que o seu nome, e faça o programa
+ ' Responder ao que é dito.
+ Nome de usuário Dim As String
+ " Nós usamos string como string é uma variável de texto baseado .
+ Console.WriteLine (" Olá, Qual é o seu nome? ") ' Peça ao usuário seu nome.
+ username = Console.ReadLine () ' armazena o nome usuários.
+ Console.WriteLine (" Olá " + nome do usuário) " A saída é Olá ' Seu nome '
+ Console.ReadLine () ' Outsputs acima.
+ ' O código acima irá lhe fazer uma pergunta seguiu imprimindo sua resposta.
+ " Outras variáveis ​​incluem Integer e usamos inteiro para números inteiros.
+ End Sub
+
+ "Três
+ Sub CalculatingWholeNumbers particulares ()
+ Console.Title = " Cálculo de Números Inteiros | Saiba X em Y Minutes"
+ Console.Write ("Primeiro número:") 'Digite um número inteiro, 1, 2, 50, 104 ect
+ Dim a As Integer = Console.ReadLine ()
+ Console.Write ("Segundo número:") 'Enter segundo número inteiro.
+ Dim b As Integer = Console.ReadLine ()
+ Dim c As Integer = a + b
+ Console.WriteLine ( c)
+ Console.ReadLine ()
+ " O texto acima é uma calculadora simples
+ End Sub
+
+ 'Quatro
+ Sub CalculatingDecimalNumbers particulares ()
+ Console.Title = " Calculando com duplo | Saiba X em Y Minutes"
+ ' Claro que gostaria de ser capaz de somar decimais .
+ " Por isso, poderia mudar o acima de Integer para Double.
+
+ " Digite um número inteiro , 1,2 , 2,4 , 50,1 , 104,9 ect
+ Console.Write ("Primeiro número:")
+ Dim a As Double = Console.ReadLine
+ Console.Write ("Segundo número:") 'Enter segundo número inteiro.
+ Dim b As Double = Console.ReadLine
+ Dim c As Double = a + b
+ Console.WriteLine ( c)
+ Console.ReadLine ()
+ " Portanto, o programa acima pode adicionar até 1,1-2,2
+ End Sub
+
+ ' Cinco
+ Private Sub WorkingCalculator ()
+ Console.Title = " A Calculadora de Trabalho | Saiba X em Y Minutes"
+ " No entanto, se você gostaria que a calculadora para subtrair, dividir , múltiplos e
+ ' somar.
+ ' Copie e cole o código acima novamente .
+ Console.Write ("Primeiro número:")
+ Dim a As Double = Console.ReadLine
+ Console.Write ("Segundo número:") 'Enter segundo número inteiro.
+ Dim b As Integer = Console.ReadLine
+ Dim c As Integer = a + b
+ Dim d As Integer = a * b
+ Dim e As Integer = a - b
+ Dim f As Integer = a / b
+
+ " Ao adicionar as linhas abaixo , somos capazes de calcular a subtração ,
+ ' multply bem como dividir os valores de a e b
+ Console.Gravar ( a.ToString ( ) + " + " + b.ToString ( ) )
+ 'Queremos pad as respostas para a esquerda por três espaços.
+ Console.WriteLine (" =" + c.ToString.PadLeft (3) )
+ Console.Gravar ( a.ToString ( ) + " * " + b.ToString ( ) )
+ Console.WriteLine (" =" + d.ToString.PadLeft (3) )
+ Console.Gravar ( a.ToString ( ) + " - " + b.ToString ( ) )
+ Console.WriteLine (" =" + e.ToString.PadLeft (3) )
+ Console.Write ( a.ToString () + "/" + b.ToString ())
+ Console.WriteLine (" =" + e.ToString.PadLeft (3) )
+ Console.ReadLine ()
+
+ End Sub
+
+ ' Seis
+ Sub UsingDoWhileLoops particulares ()
+ ' Assim como o sub privado anterior
+ ' Desta vez, perguntar se o usuário deseja continuar ( Sim ou Não ? )
+ ' Estamos usando Do While Loop , como não temos certeza se o usuário quer usar o
+ 'programa mais de uma vez .
+ Console.Title = " UsingDoWhileLoops | Saiba X em Y Minutes"
+ Dim resposta As String ' Nós usamos a variável " String" como a resposta é um texto
+ Do ' Começamos o programa com
+ Console.Write ("Primeiro número:")
+ Dim a As Double = Console.ReadLine
+ Console.Write ("Segundo número:")
+ Dim b As Integer = Console.ReadLine
+ Dim c As Integer = a + b
+ Dim d As Integer = a * b
+ Dim e As Integer = a - b
+ Dim f As Integer = a / b
+
+ Console.Gravar ( a.ToString ( ) + " + " + b.ToString ( ) )
+ Console.WriteLine (" =" + c.ToString.PadLeft (3) )
+ Console.Gravar ( a.ToString ( ) + " * " + b.ToString ( ) )
+ Console.WriteLine (" =" + d.ToString.PadLeft (3) )
+ Console.Gravar ( a.ToString ( ) + " - " + b.ToString ( ) )
+ Console.WriteLine (" =" + e.ToString.PadLeft (3) )
+ Console.Write ( a.ToString () + "/" + b.ToString ())
+ Console.WriteLine (" =" + e.ToString.PadLeft (3) )
+ Console.ReadLine ()
+ ' Faça a pergunta , se o usuário deseja continuar? Infelizmente,
+ "é sensível a maiúsculas.
+ Console.Write ( "Deseja continuar? (Sim / não )")
+ " O programa pega a variável e imprime e começa de novo.
+ answer = Console.ReadLine
+ " O comando para a variável para trabalhar seria , neste caso, " sim "
+ Loop While resposta = "yes"
+
+ End Sub
+
+ ' Sete
+ Sub UsingForLoops particulares ()
+ ' Às vezes, o programa só precisa ser executado uma vez.
+ " Neste programa vamos estar em contagem regressiva a partir de 10.
+
+ Console.Title = " Usando Para Loops | Saiba X em Y Minutes"
+ 'Declare variável e qual o número que deve contar para baixo na etapa 1,
+ ' Passo -2, -3 Passo ect.
+ Para i As Integer = 10 para 0 passo -1
+ Console.WriteLine ( i.ToString ) ' Imprime o valor do contador
+ Next i ' Calcular novo valor
+ Console.WriteLine ( "Start ") ' Vamos começar o bebê programa !
+ Console.ReadLine () ' POW ! - Talvez eu fiquei um pouco animado, então :)
+ End Sub
+
+ ' Oito
+ Private Sub ConditionalStatement ()
+ Console.Title = " Instruções condicionais | Saiba X em Y Minutes"
+ UserName Dim As String = Console.ReadLine
+ Console.WriteLine (" Olá, Qual é o seu nome? ") ' Peça ao usuário seu nome.
+ username = Console.ReadLine () ' armazena o nome usuários.
+ Se userName = " Adam " Então
+ Console.WriteLine (" Olá Adam " )
+ Console.WriteLine (" Obrigado por criar este site útil " )
+ Console.ReadLine ()
+ outro
+ Console.WriteLine (" Olá " + nome do usuário)
+ Console.WriteLine (" Você check-out www.learnxinyminutes.com " )
+ Console.ReadLine () ' Fins e imprime a declaração acima .
+ End If
+ End Sub
+
+ 'Nove
+ Private Sub IfElseStatement ()
+ Console.Title = "Se Declaração / Else | Saiba X em Y Minutes"
+ 'Às vezes é importante ter em conta mais de duas alternativas.
+ 'Às vezes, há um bom número de outros.
+ 'Quando este for o caso , mais do que uma if seria necessária .
+ 'Uma instrução if é ótimo para máquinas de venda automática . Quando o usuário digita um código.
+ ' A1 , A2, A3 , ect para selecionar um item.
+ 'Todas as opções podem ser combinadas em uma única if.
+
+ Seleção Dim Valor String = Console.ReadLine ' para a seleção
+ Console.WriteLine (" A1. Para Soda " )
+ Console.WriteLine (" A2. Para Fanta " )
+ Console.WriteLine (" A3 . Para Guaraná" )
+ Console.WriteLine (" A4. Para Coca Diet" )
+ Console.ReadLine ()
+ Se a seleção = "A1" Então
+ Console.WriteLine (" soda " )
+ Console.ReadLine ()
+ Seleção ElseIf = " A2 " Então
+ Console.WriteLine (" fanta " )
+ Console.ReadLine ()
+ Seleção ElseIf = " A3 " Então
+ Console.WriteLine ( "guaraná" )
+ Console.ReadLine ()
+ Seleção ElseIf = " A4 " Então
+ Console.WriteLine ( "coca diet" )
+ Console.ReadLine ()
+ outro
+ Console.WriteLine (" Por favor seleccione um produto" )
+ Console.ReadLine ()
+ End If
+
+ End Sub
+
+End Module
+
+```
+
+##Referências
+
+Aprendi Visual Basic no aplicativo de console. Isso me permitiu entender os princípios da programação de computador para continuar a aprender outras linguagens de programação facilmente.
+
+Eu criei um tutorial mais aprofundado do <a href="http://www.vbbootcamp.co.uk/" Title="Visual Basic Tutorial">Visual Basic</a> para aqueles que gostariam de saber mais.
+
+Toda a sintaxe deste tutorial é válida. Copie e cole o código no compilador do Visual Basic e execute (com o F5) o programa.
diff --git a/zh-cn/coffeescript-cn.html.markdown b/zh-cn/coffeescript-cn.html.markdown
new file mode 100644
index 00000000..8fb96749
--- /dev/null
+++ b/zh-cn/coffeescript-cn.html.markdown
@@ -0,0 +1,101 @@
+---
+language: coffeescript
+contributors:
+ - ["Tenor Biel", "http://github.com/L8D"]
+ - ["Xavier Yao"], "http://github.com/xavieryao"]
+translators:
+ - ["Xavier Yao"], "http://github.com/xavieryao"]
+filename: coffeescript-cn.coffee
+lang: zh-cn
+---
+
+CoffeeScript是逐句编译为JavaScript的一种小型语言,且没有运行时的解释器。
+作为JavaScript的替代品之一,CoffeeScript旨在编译人类可读、美观优雅且速度不输原生的代码,
+且编译后的代码可以在任何JavaScript运行时正确运行。
+
+参阅 [CoffeeScript官方网站](http://coffeescript.org/)以获取CoffeeScript的完整教程。
+
+``` coffeescript
+# CoffeeScript是一种很潮的编程语言,
+# 它紧随众多现代编程语言的趋势。
+# 因此正如Ruby和Python,CoffeeScript使用井号标记注释。
+
+###
+大段落注释以此为例,可以被直接编译为 '/ *' 和 '* /' 包裹的JavaScript代码。
+
+在继续之前你需要了解JavaScript的基本概念。
+
+示例中 => 后为编译后的JavaScript代码
+###
+
+# 赋值:
+number = 42 #=> var number = 42;
+opposite = true #=> var opposite = true;
+
+# 条件:
+number = -42 if opposite #=> if(opposite) { number = -42; }
+
+# 函数:
+square = (x) -> x * x #=> var square = function(x) { return x * x; }
+
+fill = (container, liquid = "coffee") ->
+ "Filling the #{container} with #{liquid}..."
+#=>var fill;
+#
+#fill = function(container, liquid) {
+# if (liquid == null) {
+# liquid = "coffee";
+# }
+# return "Filling the " + container + " with " + liquid + "...";
+#};
+
+# 区间:
+list = [1..5] #=> var list = [1, 2, 3, 4, 5];
+
+# 对象:
+math =
+ root: Math.sqrt
+ square: square
+ cube: (x) -> x * square x
+#=> var math = {
+# "root": Math.sqrt,
+# "square": square,
+# "cube": function(x) { return x * square(x); }
+#}
+
+# Splats:
+race = (winner, runners...) ->
+ print winner, runners
+#=>race = function() {
+# var runners, winner;
+# winner = arguments[0], runners = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
+# return print(winner, runners);
+#};
+
+# 存在判断:
+alert "I knew it!" if elvis?
+#=> if(typeof elvis !== "undefined" && elvis !== null) { alert("I knew it!"); }
+
+# 数组推导:
+cubes = (math.cube num for num in list)
+#=>cubes = (function() {
+# var _i, _len, _results;
+# _results = [];
+# for (_i = 0, _len = list.length; _i < _len; _i++) {
+# num = list[_i];
+# _results.push(math.cube(num));
+# }
+# return _results;
+# })();
+
+foods = ['broccoli', 'spinach', 'chocolate']
+eat food for food in foods when food isnt 'chocolate'
+#=>foods = ['broccoli', 'spinach', 'chocolate'];
+#
+#for (_k = 0, _len2 = foods.length; _k < _len2; _k++) {
+# food = foods[_k];
+# if (food !== 'chocolate') {
+# eat(food);
+# }
+#}
+```
diff --git a/zh-cn/lua-cn.html.markdown b/zh-cn/lua-cn.html.markdown
new file mode 100644
index 00000000..95a94c76
--- /dev/null
+++ b/zh-cn/lua-cn.html.markdown
@@ -0,0 +1,413 @@
+---
+language: lua
+lang: zh-cn
+contributors:
+ - ["Tyler Neylon", "http://tylerneylon.com/"]
+ - ["Rob Hoelz", "http://hoelz.ro"]
+ - ["Jakukyo Friel", "http://weakish.github.io"]
+ - ["Craig Roddin", "craig.roddin@gmail.com"]
+ - ["Amr Tamimi", "https://amrtamimi.com"]
+translators:
+ - ["Jakukyo Friel", "http://weakish.github.io"]
+---
+
+```lua
+-- 单行注释以两个连字符开头
+
+--[[
+ 多行注释
+--]]
+
+----------------------------------------------------
+-- 1. 变量和流程控制
+----------------------------------------------------
+
+num = 42 -- 所有的数字都是双精度浮点型。
+-- 别害怕,64位的双精度浮点型数字中有52位用于
+-- 保存精确的整型值; 对于52位以内的整型值,
+-- 不用担心精度问题。
+
+s = 'walternate' -- 和Python一样,字符串不可变。
+t = "也可以用双引号"
+u = [[ 多行的字符串
+ 以两个方括号
+ 开始和结尾。]]
+t = nil -- 撤销t的定义; Lua 支持垃圾回收。
+
+-- 块使用do/end之类的关键字标识:
+while num < 50 do
+ num = num + 1 -- 不支持 ++ 或 += 运算符。
+end
+
+-- If语句:
+if num > 40 then
+ print('over 40')
+elseif s ~= 'walternate' then -- ~= 表示不等于。
+ -- 像Python一样,用 == 检查是否相等 ;字符串同样适用。
+ io.write('not over 40\n') -- 默认标准输出。
+else
+ -- 默认全局变量。
+ thisIsGlobal = 5 -- 通常使用驼峰。
+
+ -- 如何定义局部变量:
+ local line = io.read() -- 读取标准输入的下一行。
+
+ -- ..操作符用于连接字符串:
+ print('Winter is coming, ' .. line)
+end
+
+-- 未定义的变量返回nil。
+-- 这不是错误:
+foo = anUnknownVariable -- 现在 foo = nil.
+
+aBoolValue = false
+
+--只有nil和false为假; 0和 ''都均为真!
+if not aBoolValue then print('twas false') end
+
+-- 'or'和 'and'短路
+-- 类似于C/js里的 a?b:c 操作符:
+ans = aBoolValue and 'yes' or 'no' --> 'no'
+
+karlSum = 0
+for i = 1, 100 do -- 范围包含两端
+ karlSum = karlSum + i
+end
+
+-- 使用 "100, 1, -1" 表示递减的范围:
+fredSum = 0
+for j = 100, 1, -1 do fredSum = fredSum + j end
+
+-- 通常,范围表达式为begin, end[, step].
+
+-- 循环的另一种结构:
+repeat
+ print('the way of the future')
+ num = num - 1
+until num == 0
+
+----------------------------------------------------
+-- 2. 函数。
+----------------------------------------------------
+
+function fib(n)
+ if n < 2 then return 1 end
+ return fib(n - 2) + fib(n - 1)
+end
+
+-- 支持闭包及匿名函数:
+function adder(x)
+ -- 调用adder时,会创建返回的函数,
+ -- 并且会记住x的值:
+ return function (y) return x + y end
+end
+a1 = adder(9)
+a2 = adder(36)
+print(a1(16)) --> 25
+print(a2(64)) --> 100
+
+-- 返回值、函数调用和赋值都可以
+-- 使用长度不匹配的list。
+-- 不匹配的接收方会被赋值nil;
+-- 不匹配的发送方会被丢弃。
+
+x, y, z = 1, 2, 3, 4
+-- x = 1、y = 2、z = 3, 而 4 会被丢弃。
+
+function bar(a, b, c)
+ print(a, b, c)
+ return 4, 8, 15, 16, 23, 42
+end
+
+x, y = bar('zaphod') --> 打印 "zaphod nil nil"
+-- 现在 x = 4, y = 8, 而值15..42被丢弃。
+
+-- 函数是一等公民,可以是局部的,也可以是全局的。
+-- 以下表达式等价:
+function f(x) return x * x end
+f = function (x) return x * x end
+
+-- 这些也是等价的:
+local function g(x) return math.sin(x) end
+local g; g = function (x) return math.sin(x) end
+-- 'local g'使得g可以自引用。
+
+-- 顺便提下,三角函数以弧度为单位。
+
+-- 用一个字符串参数调用函数,可以省略括号:
+print 'hello' --可以工作。
+
+-- 调用函数时,如果只有一个table参数,
+-- 同样可以省略括号(table详情见下):
+print {} -- 一样可以工作。
+
+----------------------------------------------------
+-- 3. Table。
+----------------------------------------------------
+
+-- Table = Lua唯一的组合数据结构;
+-- 它们是关联数组。
+-- 类似于PHP的数组或者js的对象,
+-- 它们是哈希表或者字典,也可以当初列表使用。
+
+-- 按字典/map的方式使用Table:
+
+-- Dict字面量默认使用字符串类型的key:
+t = {key1 = 'value1', key2 = false}
+
+-- 字符串key可以使用类似js的点标记:
+print(t.key1) -- 打印 'value1'.
+t.newKey = {} -- 添加新的键值对。
+t.key2 = nil -- 从table删除 key2。
+
+-- 使用任何非nil的值作为key:
+u = {['@!#'] = 'qbert', [{}] = 1729, [6.28] = 'tau'}
+print(u[6.28]) -- 打印 "tau"
+
+-- 数字和字符串的key按值匹配的
+-- table按id匹配。
+a = u['@!#'] -- 现在 a = 'qbert'.
+b = u[{}] -- 我们或许期待的是 1729, 但是得到的是nil:
+-- b = nil ,因为没有找到。
+-- 之所以没找到,是因为我们用的key与保存数据时用的不是同
+-- 一个对象。
+-- 所以字符串和数字是移植性更好的key。
+
+-- 只需要一个table参数的函数调用不需要括号:
+function h(x) print(x.key1) end
+h{key1 = 'Sonmi~451'} -- 打印'Sonmi~451'.
+
+for key, val in pairs(u) do -- 遍历Table
+ print(key, val)
+end
+
+-- _G 是一个特殊的table,用于保存所有的全局变量
+print(_G['_G'] == _G) -- 打印'true'.
+
+-- 按列表/数组的方式使用:
+
+-- 列表字面量隐式添加整数键:
+v = {'value1', 'value2', 1.21, 'gigawatts'}
+for i = 1, #v do -- #v 是列表的大小
+ print(v[i]) -- 索引从 1 开始!! 太疯狂了!
+end
+-- 'list'并非真正的类型,v 其实是一个table,
+-- 只不过它用连续的整数作为key,可以像list那样去使用。
+
+----------------------------------------------------
+-- 3.1 元表(metatable) 和元方法(metamethod)。
+----------------------------------------------------
+
+-- table的元表提供了一种机制,支持类似操作符重载的行为。
+-- 稍后我们会看到元表如何支持类似js prototype的行为。
+
+f1 = {a = 1, b = 2} -- 表示一个分数 a/b.
+f2 = {a = 2, b = 3}
+
+-- 这会失败:
+-- s = f1 + f2
+
+metafraction = {}
+function metafraction.__add(f1, f2)
+ sum = {}
+ sum.b = f1.b * f2.b
+ sum.a = f1.a * f2.b + f2.a * f1.b
+ return sum
+end
+
+setmetatable(f1, metafraction)
+setmetatable(f2, metafraction)
+
+s = f1 + f2 -- 调用在f1的元表上的__add(f1, f2) 方法
+
+-- f1, f2 没有关于元表的key,这点和js的prototype不一样。
+-- 因此你必须用getmetatable(f1)获取元表。
+-- 元表是一个普通的table,
+-- 元表的key是普通的Lua中的key,例如__add。
+
+-- 但是下面一行代码会失败,因为s没有元表:
+-- t = s + s
+-- 下面提供的与类相似的模式可以解决这个问题:
+
+-- 元表的__index 可以重载用于查找的点操作符:
+defaultFavs = {animal = 'gru', food = 'donuts'}
+myFavs = {food = 'pizza'}
+setmetatable(myFavs, {__index = defaultFavs})
+eatenBy = myFavs.animal -- 可以工作!感谢元表
+
+-- 如果在table中直接查找key失败,会使用
+-- 元表的__index 递归地重试。
+
+-- __index的值也可以是function(tbl, key)
+-- 这样可以支持自定义查找。
+
+-- __index、__add等的值,被称为元方法。
+-- 这里是一个table元方法的清单:
+
+-- __add(a, b) for a + b
+-- __sub(a, b) for a - b
+-- __mul(a, b) for a * b
+-- __div(a, b) for a / b
+-- __mod(a, b) for a % b
+-- __pow(a, b) for a ^ b
+-- __unm(a) for -a
+-- __concat(a, b) for a .. b
+-- __len(a) for #a
+-- __eq(a, b) for a == b
+-- __lt(a, b) for a < b
+-- __le(a, b) for a <= b
+-- __index(a, b) <fn or a table> for a.b
+-- __newindex(a, b, c) for a.b = c
+-- __call(a, ...) for a(...)
+
+----------------------------------------------------
+-- 3.2 与类相似的table和继承。
+----------------------------------------------------
+
+-- Lua没有内建的类;可以通过不同的方法,利用表和元表
+-- 来实现类。
+
+-- 下面是一个例子,解释在后面:
+
+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看上去像一个类;其实它是一个table。
+-- 2. 函数tablename:fn(...) 等价于
+-- 函数tablename.fn(self, ...)
+-- 冒号(:)只是添加了self作为第一个参数。
+-- 阅读7 & 8条 了解self变量是如何得到其值的。
+-- 3. newObj是类Dog的一个实例。
+-- 4. self = 被继承的类。通常self = Dog,不过继承可以改变它。
+-- 如果把newObj的元表和__index都设置为self,
+-- newObj就可以得到self的函数。
+-- 5. 备忘:setmetatable返回其第一个参数。
+-- 6. 冒号(:)的作用和第2条一样,不过这里
+-- self是一个实例,而不是类
+-- 7. 等价于Dog.new(Dog),所以在new()中,self = Dog。
+-- 8. 等价于mrDog.makeSound(mrDog); self = mrDog。
+
+----------------------------------------------------
+
+-- 继承的例子:
+
+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获得Dog的方法和变量列表。
+-- 2. 因为new()的缘故,self拥有了一个'sound' key,参见第3条。
+-- 3. 等价于LoudDog.new(LoudDog),转换一下就是
+-- Dog.new(LoudDog),这是因为LoudDog没有'new' key,
+-- 但是它的元表中有 __index = Dog。
+-- 结果: seymour的元表是LoudDog,并且
+-- LoudDog.__index = Dog。所以有seymour.key
+-- = seymour.key, LoudDog.key, Dog.key
+-- 从其中第一个有指定key的table获取。
+-- 4. 在LoudDog可以找到'makeSound'的key;
+-- 等价于LoudDog.makeSound(seymour)。
+
+-- 如果有必要,子类也可以有new(),与基类相似:
+function LoudDog:new()
+ newObj = {}
+ -- 初始化newObj
+ self.__index = self
+ return setmetatable(newObj, self)
+end
+
+----------------------------------------------------
+-- 4. 模块
+----------------------------------------------------
+
+
+--[[ 我把这部分给注释了,这样脚本剩下的部分可以运行
+
+-- 假设文件mod.lua的内容类似这样:
+local M = {}
+
+local function sayMyName()
+ print('Hrunkner')
+end
+
+function M.sayHello()
+ print('Why hello there')
+ sayMyName()
+end
+
+return M
+
+-- 另一个文件可以使用mod.lua的功能:
+local mod = require('mod') -- 运行文件mod.lua.
+
+-- require是包含模块的标准做法。
+-- require等价于: (针对没有被缓存的情况;参见后面的内容)
+local mod = (function ()
+ <contents of mod.lua>
+end)()
+-- mod.lua被包在一个函数体中,因此mod.lua的局部变量
+-- 对外不可见。
+
+-- 下面的代码可以工作,因为在这里mod = mod.lua 中的 M:
+mod.sayHello() -- Says hello to Hrunkner.
+
+-- 这是错误的;sayMyName只在mod.lua中存在:
+mod.sayMyName() -- 错误
+
+-- require返回的值会被缓存,所以一个文件只会被运行一次,
+-- 即使它被require了多次。
+
+-- 假设mod2.lua包含代码"print('Hi!')"。
+local a = require('mod2') -- 打印Hi!
+local b = require('mod2') -- 不再打印; a=b.
+
+-- dofile与require类似,但是不缓存:
+dofile('mod2') --> Hi!
+dofile('mod2') --> Hi! (再次运行,与require不同)
+
+-- loadfile加载一个lua文件,但是并不运行它。
+f = loadfile('mod2') -- Calling f() runs mod2.lua.
+
+-- loadstring是loadfile的字符串版本。
+g = loadstring('print(343)') --返回一个函数。
+g() -- 打印343; 在此之前什么也不打印。
+
+--]]
+```
+
+## 参考
+
+
+
+为什么?我非常兴奋地学习lua, 这样我就可以使用[Löve 2D游戏引擎](http://love2d.org/)来编游戏。
+
+怎么做?我从[BlackBulletIV的面向程序员的Lua指南](http://nova-fusion.com/2012/08/27/lua-for-programmers-part-1/)入门。接着我阅读了官方的[Lua编程](http://www.lua.org/pil/contents.html)一书。
+
+lua-users.org上的[Lua简明参考](http://lua-users.org/files/wiki_insecure/users/thomasl/luarefv51.pdf)应该值得一看。
+
+本文没有涉及标准库的内容:
+
+* <a href="http://lua-users.org/wiki/StringLibraryTutorial">string library</a>
+* <a href="http://lua-users.org/wiki/TableLibraryTutorial">table library</a>
+* <a href="http://lua-users.org/wiki/MathLibraryTutorial">math library</a>
+* <a href="http://lua-users.org/wiki/IoLibraryTutorial">io library</a>
+* <a href="http://lua-users.org/wiki/OsLibraryTutorial">os library</a>
+
+使用Lua,欢乐常在!