[lua/*] remove HTML tags

This commit is contained in:
Boris Verkhovskiy 2024-06-03 05:37:35 -06:00
parent 3ea2b0b29f
commit f18b36c3bf
8 changed files with 361 additions and 366 deletions

View File

@ -21,7 +21,7 @@ lang: de-de
num = 42 -- Alle Nummern sind vom Typ: Double. num = 42 -- Alle Nummern sind vom Typ: Double.
-- Werd nicht nervös, 64-Bit Double haben 52 Bits zum Speichern von exakten -- Werd nicht nervös, 64-Bit Double haben 52 Bits zum Speichern von exakten
-- Ganzzahlen; Maschinen-Genauigkeit ist kein Problem für Ganzzahlen kleiner als -- Ganzzahlen; Maschinen-Genauigkeit ist kein Problem für Ganzzahlen kleiner als
-- 52 Bit. -- 52 Bit.
s = 'walternate' -- Zeichenketten sind unveränderlich, wie bei Python. s = 'walternate' -- Zeichenketten sind unveränderlich, wie bei Python.
@ -404,23 +404,22 @@ g() -- Ausgabe 343; Vorher kam keine Ausgabe.
## Referenzen ## Referenzen
Ich war so begeistert Lua zu lernen, damit ich Spiele mit <a href="http://love2d.org/">Love 2D game engine</a> programmieren konnte. Ich war so begeistert Lua zu lernen, damit ich Spiele mit [LÖVE game engine](http://love2d.org/) programmieren konnte.
Ich habe angefangen mit <a href="http://nova-fusion.com/2012/08/27/lua-for-programmers-part-1/">BlackBulletIV's Lua for programmers</a>. Ich habe angefangen mit [BlackBulletIV's Lua for programmers](http://nova-fusion.com/2012/08/27/lua-for-programmers-part-1/).
Danach habe ich das offizielle Lua Buch gelesen: <a href="http://www.lua.org/pil/contents.html">Programming in Lua</a> Danach habe ich das offizielle Lua Buch gelesen: [Programming in Lua](http://www.lua.org/pil/contents.html)
Es kann auch hilfreich sein hier vorbeizuschauen: <a href="http://lua-users.org/files/wiki_insecure/users/thomasl/luarefv51.pdf">Lua short Es kann auch hilfreich sein hier vorbeizuschauen: [Lua short reference](http://lua-users.org/files/wiki_insecure/users/thomasl/luarefv51.pdf)
reference</a>
Wichtige Themen die hier nicht angesprochen wurden; die Standard-Bibliotheken: Wichtige Themen die hier nicht angesprochen wurden; die Standard-Bibliotheken:
* <a href="http://lua-users.org/wiki/StringLibraryTutorial">string library</a> * [`string` library](http://lua-users.org/wiki/StringLibraryTutorial)
* <a href="http://lua-users.org/wiki/TableLibraryTutorial">table library</a> * [`table` library](http://lua-users.org/wiki/TableLibraryTutorial)
* <a href="http://lua-users.org/wiki/MathLibraryTutorial">math library</a> * [`math` library](http://lua-users.org/wiki/MathLibraryTutorial)
* <a href="http://lua-users.org/wiki/IoLibraryTutorial">io library</a> * [`io` library](http://lua-users.org/wiki/IoLibraryTutorial)
* <a href="http://lua-users.org/wiki/OsLibraryTutorial">os library</a> * [`os` library](http://lua-users.org/wiki/OsLibraryTutorial)
Übrigends, die gesamte Datei ist gültiges Lua. Speichere sie als learn.lua und Übrigends, die gesamte Datei ist gültiges Lua. Speichere sie als learn.lua und
starte sie als "lua learn.lua" ! starte sie als "`lua learn.lua`" !
Die Erstfassung ist von tylerneylon.com, und ist auch hier verfügbar: <a href="https://gist.github.com/tylerneylon/5853042">GitHub gist</a>. Viel Spaß mit Lua! Die Erstfassung ist von tylerneylon.com, und ist auch hier verfügbar: [GitHub gist](https://gist.github.com/tylerneylon/5853042). Viel Spaß mit Lua!

View File

@ -419,7 +419,7 @@ g() -- Imprime '343', nada es impreso antes de esto.
## Referencias ## Referencias
Estaba emocionado por aprender lua para poder crear juegos Estaba emocionado por aprender lua para poder crear juegos
con el motor de juegos [Love 2D](http://love2d.org/). Ese es el por qué. con el motor de juegos [LÖVE](http://love2d.org/). Ese es el por qué.
Empecé con [BlackBulletIV para programadores Lua](https://ebens.me/posts/lua-for-programmers-part-1/). Empecé con [BlackBulletIV para programadores Lua](https://ebens.me/posts/lua-for-programmers-part-1/).
Luego, leí el libro oficial de [Programación en Lua](http://www.lua.org/pil/contents.html). Luego, leí el libro oficial de [Programación en Lua](http://www.lua.org/pil/contents.html).
@ -433,10 +433,10 @@ Los principales temas no cubiertos son las librerías estándar:
* [Librería de strings](http://lua-users.org/wiki/StringLibraryTutorial) * [Librería de strings](http://lua-users.org/wiki/StringLibraryTutorial)
* [Librería de tablas](http://lua-users.org/wiki/TableLibraryTutorial) * [Librería de tablas](http://lua-users.org/wiki/TableLibraryTutorial)
* [Librería de matemáticas](http://lua-users.org/wiki/MathLibraryTutorial) * [Librería de matemáticas](http://lua-users.org/wiki/MathLibraryTutorial)
* [Librería de Entrada/Salida (io)](http://lua-users.org/wiki/IoLibraryTutorial) * [Librería de Entrada/Salida (`io`)](http://lua-users.org/wiki/IoLibraryTutorial)
* [Libreria de Sistema Operativo (os)](http://lua-users.org/wiki/OsLibraryTutorial) * [Libreria de Sistema Operativo (`os`)](http://lua-users.org/wiki/OsLibraryTutorial)
Por cierto, el archivo entero es código Lua válido. ¡Guárdelo como Por cierto, el archivo entero es código Lua válido. ¡Guárdelo como
aprendiendo.lua y ejecútelo con el comando "lua aprendiendo.lua" ! aprendiendo.lua y ejecútelo con el comando "`lua aprendiendo.lua`" !
¡Que se divierta con lua! ¡Que se divierta con lua!

View File

@ -12,7 +12,7 @@ lang: fr-fr
-- Les commentaires unilignes commencent par un double tiret. -- Les commentaires unilignes commencent par un double tiret.
--[[ --[[
Les doubles crochets à la suite du double tiret Les doubles crochets à la suite du double tiret
permettent d'insérer des commentaires multilignes. permettent d'insérer des commentaires multilignes.
--]] --]]
@ -123,7 +123,7 @@ end
x, y = bar('zaphod') --> affiche "zaphod nil nil" x, y = bar('zaphod') --> affiche "zaphod nil nil"
-- x = 4, y = 8, les valeurs 15 à 42 sont ignorées. -- x = 4, y = 8, les valeurs 15 à 42 sont ignorées.
-- Les fonctions sont des valeurs de première classe -- Les fonctions sont des valeurs de première classe
-- et peuvent être locales/globales. -- et peuvent être locales/globales.
-- Les déclarations suivantes sont identiques: -- Les déclarations suivantes sont identiques:
function f(x) return x * x end function f(x) return x * x end
@ -139,7 +139,7 @@ local g = function(x) return math.sin(x) end
-- À moins de déclarer la fonction auparavant: -- À moins de déclarer la fonction auparavant:
local g; g = function (x) return math.sin(x) end local g; g = function (x) return math.sin(x) end
-- À propos, les fonctions trigonométriques interprètent -- À propos, les fonctions trigonométriques interprètent
-- leurs arguments en radians. -- leurs arguments en radians.
print(math.cos(math.pi)) -- affiche "-1" print(math.cos(math.pi)) -- affiche "-1"
print(math.sin(math.pi)) -- affiche "0" print(math.sin(math.pi)) -- affiche "0"
@ -250,7 +250,7 @@ myFavs = {food = 'pizza'}
setmetatable(myFavs, {__index = defaultFavs}) setmetatable(myFavs, {__index = defaultFavs})
eatenBy = myFavs.animal -- Affiche "gru"! merci à la métatable! eatenBy = myFavs.animal -- Affiche "gru"! merci à la métatable!
-- Ainsi donc, un accès direct à une valeur dans une table via une clé -- Ainsi donc, un accès direct à une valeur dans une table via une clé
-- inexistante (ce qui normalement retourne "nil") conduira à exploiter -- inexistante (ce qui normalement retourne "nil") conduira à exploiter
-- le champ __index de la métatable. Cela peut être récursif. -- le champ __index de la métatable. Cela peut être récursif.
@ -281,7 +281,7 @@ eatenBy = myFavs.animal -- Affiche "gru"! merci à la métatable!
---------------------------------------------------- ----------------------------------------------------
-- Lua n'implémente pas d'orienté objet par défaut. -- Lua n'implémente pas d'orienté objet par défaut.
-- Mais il reste possible d'imiter de plusieurs manières -- Mais il reste possible d'imiter de plusieurs manières
-- le concept de "classe" grâce aux tables et aux métatables. -- le concept de "classe" grâce aux tables et aux métatables.
-- L'explication pour l'exemple qui suit vient juste après. -- L'explication pour l'exemple qui suit vient juste après.
@ -302,9 +302,9 @@ mrDog = Dog:new() -- 7.
mrDog:makeSound() -- 'Je dis: woof! -- 8. mrDog:makeSound() -- 'Je dis: woof! -- 8.
-- 1. Dog agit comme une classe; c'est une simple table. -- 1. Dog agit comme une classe; c'est une simple table.
-- 2. L'expression tbl:fn(...) est identique à -- 2. L'expression tbl:fn(...) est identique à
-- tbl.fn(self, ...) -- tbl.fn(self, ...)
-- La notation : permet de passer par défaut un premier -- La notation : permet de passer par défaut un premier
-- argument appelé "self" à la fonction tbl.fn -- argument appelé "self" à la fonction tbl.fn
-- Voir 7 & 8 ci-après pour comprendre comment self prend -- Voir 7 & 8 ci-après pour comprendre comment self prend
-- sa valeur. -- sa valeur.
@ -388,7 +388,7 @@ local mod = (function ()
<contenu de mod.lua> <contenu de mod.lua>
end)() end)()
-- Comme si le contenu de mod.lua était enveloppé dans le corps d'une fonction, -- Comme si le contenu de mod.lua était enveloppé dans le corps d'une fonction,
-- si bien que les variables locales contenues dans mod.lua sont -- si bien que les variables locales contenues dans mod.lua sont
-- inaccessibles en dehors de ce module. -- inaccessibles en dehors de ce module.
-- Le code suivant fonctionne car mod = M (dans mod.lua): -- Le code suivant fonctionne car mod = M (dans mod.lua):
@ -423,27 +423,27 @@ g() -- Affiche 343; Rien n'est affiché avant cet appel.
*Les références qui suivent sont en Anglais.* *Les références qui suivent sont en Anglais.*
Les sujets non abordés dans ce tutoriel sont couverts en intégralité par Les sujets non abordés dans ce tutoriel sont couverts en intégralité par
les librairies standard: les librairies standard:
* La librairie <a href="http://lua-users.org/wiki/StringLibraryTutorial">string</a> * La librairie [`string`](http://lua-users.org/wiki/StringLibraryTutorial)
* La librairie <a href="http://lua-users.org/wiki/TableLibraryTutorial">table</a> * La librairie [`table`](http://lua-users.org/wiki/TableLibraryTutorial)
* La librairie <a href="http://lua-users.org/wiki/MathLibraryTutorial">math</a> * La librairie [`math`](http://lua-users.org/wiki/MathLibraryTutorial)
* La librairie <a href="http://lua-users.org/wiki/IoLibraryTutorial">io</a> * La librairie [`io`](http://lua-users.org/wiki/IoLibraryTutorial)
* La librairie <a href="http://lua-users.org/wiki/OsLibraryTutorial">os</a> * La librairie [`os`](http://lua-users.org/wiki/OsLibraryTutorial)
Autres références complémentaires: Autres références complémentaires:
* <a href="http://nova-fusion.com/2012/08/27/lua-for-programmers-part-1/">Lua pour programmeurs</a> * [Lua pour programmeurs](http://nova-fusion.com/2012/08/27/lua-for-programmers-part-1/)
* <a href="lua-users.org/files/wiki_insecure/users/thomasl/luarefv51.pdf">Référence condensée de Lua</a> * [Référence condensée de Lua](lua-users.org/files/wiki_insecure/users/thomasl/luarefv51.pdf)
* <a href="http://www.lua.org/pil/contents.html">Programmer en Lua</a> * [Programmer en Lua](http://www.lua.org/pil/contents.html)
* <a href="http://www.lua.org/manual/">Les manuels de référence Lua</a> * [Les manuels de référence Lua](http://www.lua.org/manual/)
A propos, ce fichier est exécutable. Sauvegardez-le sous le nom *learn.lua* et A propos, ce fichier est exécutable. Sauvegardez-le sous le nom *learn.lua* et
exécutez-le avec la commande `lua learn.lua` ! exécutez-le avec la commande "`lua learn.lua`" !
Ce tutoriel a été originalement écrit pour <a href="tylerneylon.com">tylerneylon.com</a> et est aussi Ce tutoriel a été originalement écrit pour [tylerneylon.com](tylerneylon.com) et est aussi
disponible en tant que <a href="https://gist.github.com/tylerneylon/5853042">gist</a>. disponible en tant que [gist](https://gist.github.com/tylerneylon/5853042).
Il a été traduit en français par Roland Yonaba (voir son <a href="http://github.com/Yonaba">GitHub</a>). Il a été traduit en français par Roland Yonaba (voir son [GitHub](http://github.com/Yonaba)).
Amusez-vous bien avec Lua! Amusez-vous bien avec Lua!

View File

@ -21,9 +21,9 @@ filename: learnlua-kr.lua
---------------------------------------------------- ----------------------------------------------------
num = 42 -- 모든 숫자는 double입니다. num = 42 -- 모든 숫자는 double입니다.
-- 놀랄 필요는 없습니다. 64비트 double은 -- 놀랄 필요는 없습니다. 64비트 double은
-- 정확한 int 값을 저장하기 위해 52비트로 구성돼 -- 정확한 int 값을 저장하기 위해 52비트로 구성돼
-- 있습니다. 52비트 이하의 int 값에 대해서는 -- 있습니다. 52비트 이하의 int 값에 대해서는
-- 장비 정밀도와 관련된 문제가 생기지 않습니다. -- 장비 정밀도와 관련된 문제가 생기지 않습니다.
s = 'walternate' -- 파이썬과 같은 불변 문자열 s = 'walternate' -- 파이썬과 같은 불변 문자열
@ -42,7 +42,7 @@ end
if num > 40 then if num > 40 then
print('40 이상') print('40 이상')
elseif s ~= 'walternate' then -- ~=은 '같지 않다'입니다. elseif s ~= 'walternate' then -- ~=은 '같지 않다'입니다.
-- 동일성 검사는 파이썬과 마찬가지로 ==입니다. -- 동일성 검사는 파이썬과 마찬가지로 ==입니다.
-- 문자열에도 쓸 수 있습니다. -- 문자열에도 쓸 수 있습니다.
io.write('not over 40\n') -- 기본적으로 stdout에 씁니다. io.write('not over 40\n') -- 기본적으로 stdout에 씁니다.
else else
@ -198,7 +198,7 @@ end
---------------------------------------------------- ----------------------------------------------------
-- 테이블은 테이블에 연산자 오버로딩을 가능하게 하는 메타테이블을 -- 테이블은 테이블에 연산자 오버로딩을 가능하게 하는 메타테이블을
-- 가질 수 있습니다. 나중에 메타테이블이 어떻게 자바스크립트 -- 가질 수 있습니다. 나중에 메타테이블이 어떻게 자바스크립트
-- 프로토타입과 같은 행위를 지원하는지 살펴보겠습니다. -- 프로토타입과 같은 행위를 지원하는지 살펴보겠습니다.
f1 = {a = 1, b = 2} -- 분수 a/b를 표현 f1 = {a = 1, b = 2} -- 분수 a/b를 표현
@ -220,7 +220,7 @@ setmetatable(f2, metafraction)
s = f1 + f2 -- f1의 메타테이블을 대상으로 __add(f1, f2)를 호출 s = f1 + f2 -- f1의 메타테이블을 대상으로 __add(f1, f2)를 호출
-- f1과 f2는 자바스크립트의 프로토타입과 달리 각 메타테이블에 대한 -- f1과 f2는 자바스크립트의 프로토타입과 달리 각 메타테이블에 대한
-- 키가 없어서 getmetatable(f1)과 같이 받아와야 합니다. -- 키가 없어서 getmetatable(f1)과 같이 받아와야 합니다.
-- 메타테이블은 __add 같은 루아가 알고 있는 키가 지정된 일반 테이블입니다. -- 메타테이블은 __add 같은 루아가 알고 있는 키가 지정된 일반 테이블입니다.
@ -290,11 +290,11 @@ mrDog:makeSound() -- 'I say woof' -- 8.
-- self가 값을 어떻게 얻는지 궁금하다면 아래의 7과 8을 읽어보세요. -- self가 값을 어떻게 얻는지 궁금하다면 아래의 7과 8을 읽어보세요.
-- 3. newObj는 Dog 클래스의 인스턴스가 됩니다. -- 3. newObj는 Dog 클래스의 인스턴스가 됩니다.
-- 4. self = 인스턴스화되는 클래스. -- 4. self = 인스턴스화되는 클래스.
-- 주로 self = Dog이지만 상속을 이용하면 이것을 바꿀 수 있습니다. -- 주로 self = Dog이지만 상속을 이용하면 이것을 바꿀 수 있습니다.
-- newObj의 메타테이블과 self의 __index를 모두 self에 설정하면 -- newObj의 메타테이블과 self의 __index를 모두 self에 설정하면
-- newObj가 self의 함수를 갖게 됩니다. -- newObj가 self의 함수를 갖게 됩니다.
-- 5. 참고: setmetatable은 첫 번째 인자를 반환합니다. -- 5. 참고: setmetatable은 첫 번째 인자를 반환합니다.
-- 6. :는 2에서 설명한 것과 같이 동작하지만 이번에는 self가 -- 6. :는 2에서 설명한 것과 같이 동작하지만 이번에는 self가
-- 클래스가 아닌 인스턴스라고 예상할 수 있습니다. -- 클래스가 아닌 인스턴스라고 예상할 수 있습니다.
-- 7. Dog.new(Dog)과 같으므로 new()에서는 self = Dog입니다. -- 7. Dog.new(Dog)과 같으므로 new()에서는 self = Dog입니다.
-- 8. mrDog.makeSound(mrDog)과 같으므로 self = mrDog입니다. -- 8. mrDog.makeSound(mrDog)과 같으므로 self = mrDog입니다.
@ -319,10 +319,10 @@ seymour:makeSound() -- 'woof woof woof' -- 4.
-- 메타테이블에서 __index = Dog이기 때문에 Dog.new(LoudDog)으로 -- 메타테이블에서 __index = Dog이기 때문에 Dog.new(LoudDog)으로
-- 변환됩니다. -- 변환됩니다.
-- 결과: seymour의 메타테이블은 LoudDog이고 LoudDog.__index는 -- 결과: seymour의 메타테이블은 LoudDog이고 LoudDog.__index는
-- LoudDog입니다. 따라서 seymour.key는 seymour.key, -- LoudDog입니다. 따라서 seymour.key는 seymour.key,
-- LoudDog.key, Dog.key와 같을 것이며, 지정한 키에 어떤 테이블이 -- LoudDog.key, Dog.key와 같을 것이며, 지정한 키에 어떤 테이블이
-- 오든 상관없을 것입니다. -- 오든 상관없을 것입니다.
-- 4. 'makeSound' 키는 LoudDog에서 발견할 수 있습니다. -- 4. 'makeSound' 키는 LoudDog에서 발견할 수 있습니다.
-- 이것은 LoudDog.makeSound(seymour)와 같습니다. -- 이것은 LoudDog.makeSound(seymour)와 같습니다.
-- 필요할 경우, 하위 클래스의 new()는 기반 클래스의 new()와 유사합니다. -- 필요할 경우, 하위 클래스의 new()는 기반 클래스의 new()와 유사합니다.
@ -338,7 +338,7 @@ end
---------------------------------------------------- ----------------------------------------------------
--[[ 여기서 주석을 제거하면 이 스크립트의 나머지 부분은 --[[ 여기서 주석을 제거하면 이 스크립트의 나머지 부분은
-- 실행 가능한 상태가 됩니다. -- 실행 가능한 상태가 됩니다.
``` ```
@ -395,27 +395,27 @@ g() -- 343이 출력됩니다. 그전까지는 아무것도 출력되지 않습
## 참고자료 ## 참고자료
루아를 배우는 일이 흥미진진했던 이유는 <a href="http://love2d.org/">Love 2D 게임 엔진</a>을 이용해 루아를 배우는 일이 흥미진진했던 이유는 [LÖVE 게임 엔진](http://love2d.org/)을 이용해
게임을 만들 수 있었기 때문입니다. 이것이 제가 루아를 배운 이유입니다. 게임을 만들 수 있었기 때문입니다. 이것이 제가 루아를 배운 이유입니다.
저는 <a href="http://nova-fusion.com/2012/08/27/lua-for-programmers-part-1/">BlackBulletIV의 "프로그래머를 위한 루아"</a> 저는 [BlackBulletIV의 "프로그래머를 위한 루아"](http://nova-fusion.com/2012/08/27/lua-for-programmers-part-1/)
시작했습니다. 그다음으로 공식 <a href="http://www.lua.org/pil/contents.html">"프로그래밍 루아"</a> 책을 읽었습니다. 시작했습니다. 그다음으로 공식 ["프로그래밍 루아"](http://www.lua.org/pil/contents.html) 책을 읽었습니다.
그렇게 루아를 배웠습니다. 그렇게 루아를 배웠습니다.
lua-users.org에 있는 <a href="http://lua-users.org/files/wiki_insecure/users/thomasl/luarefv51.pdf">짧은 루아 레퍼런스</a> lua-users.org에 있는 [짧은 루아 레퍼런스](http://lua-users.org/files/wiki_insecure/users/thomasl/luarefv51.pdf)
읽어두면 도움될지도 모르겠습니다. 읽어두면 도움될지도 모르겠습니다.
여기서는 표준 라이브러리에 관해서는 다루지 않았습니다. 여기서는 표준 라이브러리에 관해서는 다루지 않았습니다.
* <a href="http://lua-users.org/wiki/StringLibraryTutorial">string 라이브러리</a> * [`string` 라이브러리](http://lua-users.org/wiki/StringLibraryTutorial)
* <a href="http://lua-users.org/wiki/TableLibraryTutorial">table 라이브러리</a> * [`table` 라이브러리](http://lua-users.org/wiki/TableLibraryTutorial)
* <a href="http://lua-users.org/wiki/MathLibraryTutorial">math 라이브러리</a> * [`math` 라이브러리](http://lua-users.org/wiki/MathLibraryTutorial)
* <a href="http://lua-users.org/wiki/IoLibraryTutorial">io 라이브러리</a> * [`io` 라이브러리](http://lua-users.org/wiki/IoLibraryTutorial)
* <a href="http://lua-users.org/wiki/OsLibraryTutorial">os 라이브러리</a> * [`os` 라이브러리](http://lua-users.org/wiki/OsLibraryTutorial)
그나저나 이 파일 전체는 유효한 루아 프로그램입니다. 이 파일을 그나저나 이 파일 전체는 유효한 루아 프로그램입니다. 이 파일을
learn.lua로 저장한 후 "lua learn.lua"를 실행해 보세요! learn.lua로 저장한 후 "`lua learn.lua`"를 실행해 보세요!
이 글은 tylerneylon.com에 처음으로 써본 글이며, 이 글은 tylerneylon.com에 처음으로 써본 글이며,
<a href="https://gist.github.com/tylerneylon/5853042">GitHub의 Gist</a>에서도 확인할 수 있습니다. [GitHub의 Gist](https://gist.github.com/tylerneylon/5853042)에서도 확인할 수 있습니다.
루아로 즐거운 시간을 보내세요! 루아로 즐거운 시간을 보내세요!

View File

@ -390,31 +390,29 @@ g() -- Prints out 343; nothing printed before now.
## Community ## Community
If you need support join the official Lua [mailing list](https://www.lua.org/lua-l.html), [irc channel](http://lua-users.org/wiki/IrcChannel), or [forum](https://luaforum.com). If you need support join the official Lua [mailing list](https://www.lua.org/lua-l.html), [IRC channel](http://lua-users.org/wiki/IrcChannel), or [forum](https://luaforum.com).
## References ## References
I was excited to learn Lua so I could make games I was excited to learn Lua so I could make games
with the <a href="http://love2d.org/">Love 2D game engine</a>. That's the why. with the [LÖVE game engine](http://love2d.org/). That's the why.
I started with <a href="https://ebens.me/posts/lua-for-programmers-part-1/">BlackBulletIV's Lua for programmers</a>. I started with [BlackBulletIV's Lua for programmers](https://ebens.me/posts/lua-for-programmers-part-1/).
Next I read the official <a href="http://www.lua.org/pil/contents.html">Programming in Lua</a> book. Next I read the official [Programming in Lua](http://www.lua.org/pil/contents.html) book.
That's the how. That's the how.
It might be helpful to check out the <a href="http://lua-users.org/wiki/LuaShortReference">Lua short It might be helpful to check out the [Lua short reference](http://lua-users.org/wiki/LuaShortReference) on lua-users.org.
reference</a> on lua-users.org.
The main topics not covered are standard libraries: The main topics not covered are standard libraries:
* <a href="http://lua-users.org/wiki/StringLibraryTutorial">string library</a> * [`string` library](http://lua-users.org/wiki/StringLibraryTutorial)
* <a href="http://lua-users.org/wiki/TableLibraryTutorial">table library</a> * [`table` library](http://lua-users.org/wiki/TableLibraryTutorial)
* <a href="http://lua-users.org/wiki/MathLibraryTutorial">math library</a> * [`math` library](http://lua-users.org/wiki/MathLibraryTutorial)
* <a href="http://lua-users.org/wiki/IoLibraryTutorial">io library</a> * [`io` library](http://lua-users.org/wiki/IoLibraryTutorial)
* <a href="http://lua-users.org/wiki/OsLibraryTutorial">os library</a> * [`os` library](http://lua-users.org/wiki/OsLibraryTutorial)
By the way, the entire file is valid Lua; save it By the way, the entire file is valid Lua; save it
as learn.lua and run it with "lua learn.lua" ! as learn.lua and run it with "`lua learn.lua`" !
This was first written for tylerneylon.com, and is This was first written for tylerneylon.com, and is
also available as a <a href="https://gist.github.com/tylerneylon/5853042">GitHub gist</a>. Have fun with Lua! also available as a [GitHub gist](https://gist.github.com/tylerneylon/5853042). Have fun with Lua!

View File

@ -397,26 +397,26 @@ g() -- Imprime 343; nada foi impresso antes disso.
## Referências ## Referências
Fiquei bastante animado para aprender Lua pois consegui fazer jogos Fiquei bastante animado para aprender Lua pois consegui fazer jogos
com a <a href="http://love2d.org/">Love 2D engine de jogos</a>. com a [LÖVE engine de jogos](http://love2d.org/).
Eu comecei com <a href="http://nova-fusion.com/2012/08/27/lua-for-programmers-part-1/">BlackBulletIV's para programadores LUA</a>. Eu comecei com [BlackBulletIV's para programadores LUA](http://nova-fusion.com/2012/08/27/lua-for-programmers-part-1/).
Em seguida, eu li a documentação oficial <a href="https://www.lua.org/manual/5.1/pt/index.html#contents">Programando em Lua</a>. Em seguida, eu li a documentação oficial [Programando em Lua](https://www.lua.org/manual/5.1/pt/index.html#contents).
É assim que se começa. É assim que se começa.
Pode ser útil conferir <a href="http://lua-users.org/files/wiki_insecure/users/thomasl/luarefv51.pdf">Uma pequena referencia sobre LUA</a> em lua-users.org. Pode ser útil conferir [Uma pequena referencia sobre LUA](http://lua-users.org/files/wiki_insecure/users/thomasl/luarefv51.pdf) em lua-users.org.
Os principais tópicos não cobertos, são as bibliotecas padrões: Os principais tópicos não cobertos, são as bibliotecas padrões:
- <a href="http://lua-users.org/wiki/StringLibraryTutorial">Biblioteca de strings</a> - [Biblioteca de strings](http://lua-users.org/wiki/StringLibraryTutorial)
- <a href="http://lua-users.org/wiki/TableLibraryTutorial">Biblioteca de tabelas</a> - [Biblioteca de tabelas](http://lua-users.org/wiki/TableLibraryTutorial)
- <a href="http://lua-users.org/wiki/MathLibraryTutorial">Biblioteca de matemática</a> - [Biblioteca de matemática](http://lua-users.org/wiki/MathLibraryTutorial)
- <a href="http://lua-users.org/wiki/IoLibraryTutorial">Biblioteca de entrada/saída</a> - [Biblioteca de entrada/saída](http://lua-users.org/wiki/IoLibraryTutorial)
- <a href="http://lua-users.org/wiki/OsLibraryTutorial">Biblioteca do sistema operacional</a> - [Biblioteca do sistema operacional](http://lua-users.org/wiki/OsLibraryTutorial)
A propósito, todo este arquivo é um código LUA válido, salve-o como A propósito, todo este arquivo é um código LUA válido, salve-o como
aprenda.lua e rode-o com "lua aprenda.lua" ! aprenda.lua e rode-o com "`lua aprenda.lua`" !
Este guia foi escrito pela primeira vez por tylerneylon.com, e agora Este guia foi escrito pela primeira vez por tylerneylon.com, e agora
também disponível em <a href="https://gist.github.com/tylerneylon/5853042">GitHub gist</a>. E também em português. também disponível em [GitHub gist](https://gist.github.com/tylerneylon/5853042). E também em português.
Se divirta com lua Se divirta com lua

View File

@ -404,22 +404,22 @@ g() -- Напишет 343.
## Примечание (от автора) ## Примечание (от автора)
Мне было интересно изучить Lua, чтобы делать игры при помощи <a href="http://love2d.org/">игрового движка LÖVE</a>. Мне было интересно изучить Lua, чтобы делать игры при помощи [игрового движка LÖVE](http://love2d.org/).
Я начинал с <a href="http://nova-fusion.com/2012/08/27/lua-for-programmers-part-1/">BlackBulletIV's Lua for programmers</a>. Я начинал с [BlackBulletIV's Lua for programmers](http://nova-fusion.com/2012/08/27/lua-for-programmers-part-1/).
Затем я прочитал официальную <a href="http://www.lua.org/pil/contents.html">Документацию по Lua</a>. Затем я прочитал официальную [Документацию по Lua](http://www.lua.org/pil/contents.html).
Также может быть полезной <a href="http://lua-users.org/files/wiki_insecure/users/thomasl/luarefv51.pdf">Краткая справка по Lua</a> на lua-users.org. Также может быть полезной [Краткая справка по Lua](http://lua-users.org/files/wiki_insecure/users/thomasl/luarefv51.pdf) на lua-users.org.
Ещё из основных тем не охвачены стандартные библиотеки: Ещё из основных тем не охвачены стандартные библиотеки:
* <a href="http://lua-users.org/wiki/StringLibraryTutorial">библиотека string</a> * [библиотека `string`](http://lua-users.org/wiki/StringLibraryTutorial)
* <a href="http://lua-users.org/wiki/TableLibraryTutorial">библиотека table</a> * [библиотека `table`](http://lua-users.org/wiki/TableLibraryTutorial)
* <a href="http://lua-users.org/wiki/MathLibraryTutorial">библиотека math</a> * [библиотека `math`](http://lua-users.org/wiki/MathLibraryTutorial)
* <a href="http://lua-users.org/wiki/IoLibraryTutorial">библиотека io</a> * [библиотека `io`](http://lua-users.org/wiki/IoLibraryTutorial)
* <a href="http://lua-users.org/wiki/OsLibraryTutorial">библиотека os</a> * [библиотека `os`](http://lua-users.org/wiki/OsLibraryTutorial)
Кстати, весь файл написан на Lua; сохраните его как learn.lua и запустите при помощи "lua learn.lua" ! Кстати, весь файл написан на Lua; сохраните его как learn.lua и запустите при помощи `lua learn.lua`
Изначально эта статья была написана для tylerneylon.com. Изначально эта статья была написана для tylerneylon.com.
Также она доступна как <a href="https://gist.github.com/tylerneylon/5853042">GitHub gist</a>. Удачи с Lua! Также она доступна как [GitHub gist](https://gist.github.com/tylerneylon/5853042). Удачи с Lua!

View File

@ -1,7 +1,7 @@
--- ---
language: Lua language: Lua
lang: zh-cn lang: zh-cn
contributors: contributors:
- ["Tyler Neylon", "http://tylerneylon.com/"] - ["Tyler Neylon", "http://tylerneylon.com/"]
- ["Rob Hoelz", "http://hoelz.ro"] - ["Rob Hoelz", "http://hoelz.ro"]
- ["Jakukyo Friel", "http://weakish.github.io"] - ["Jakukyo Friel", "http://weakish.github.io"]
@ -13,411 +13,409 @@ filename: lua-cn.lua
--- ---
```lua ```lua
-- 单行注释以两个连字符开头 -- 单行注释以两个连字符开头
--[[ --[[
多行注释 多行注释
--]] --]]
---------------------------------------------------- ----------------------------------------------------
-- 1. 变量和流程控制 -- 1. 变量和流程控制
---------------------------------------------------- ----------------------------------------------------
num = 42 -- 所有的数字都是双精度浮点型。 num = 42 -- 所有的数字都是双精度浮点型。
-- 别害怕64位的双精度浮点型数字中有52位用于 -- 别害怕64位的双精度浮点型数字中有52位用于
-- 保存精确的整型值; 对于52位以内的整型值 -- 保存精确的整型值; 对于52位以内的整型值
-- 不用担心精度问题。 -- 不用担心精度问题。
s = 'walternate' -- 和Python一样字符串不可变。 s = 'walternate' -- 和Python一样字符串不可变。
t = "也可以用双引号" t = "也可以用双引号"
u = [[ 多行的字符串 u = [[ 多行的字符串
以两个方括号 以两个方括号
开始和结尾。]] 开始和结尾。]]
t = nil -- 撤销t的定义; Lua 支持垃圾回收。 t = nil -- 撤销t的定义; Lua 支持垃圾回收。
-- 块使用do/end之类的关键字标识 -- 块使用do/end之类的关键字标识
while num < 50 do while num < 50 do
num = num + 1 -- 不支持 ++ 或 += 运算符。 num = num + 1 -- 不支持 ++ 或 += 运算符。
end end
-- If语句 -- If语句
if num > 40 then if num > 40 then
print('over 40') print('over 40')
elseif s ~= 'walternate' then -- ~= 表示不等于。 elseif s ~= 'walternate' then -- ~= 表示不等于。
-- 像Python一样用 == 检查是否相等 ;字符串同样适用。 -- 像Python一样用 == 检查是否相等 ;字符串同样适用。
io.write('not over 40\n') -- 默认标准输出。 io.write('not over 40\n') -- 默认标准输出。
else else
-- 默认全局变量。 -- 默认全局变量。
thisIsGlobal = 5 -- 通常使用驼峰。 thisIsGlobal = 5 -- 通常使用驼峰。
-- 如何定义局部变量: -- 如何定义局部变量:
local line = io.read() -- 读取标准输入的下一行。 local line = io.read() -- 读取标准输入的下一行。
-- ..操作符用于连接字符串: -- ..操作符用于连接字符串:
print('Winter is coming, ' .. line) print('Winter is coming, ' .. line)
end end
-- 未定义的变量返回nil。 -- 未定义的变量返回nil。
-- 这不是错误: -- 这不是错误:
foo = anUnknownVariable -- 现在 foo = nil. foo = anUnknownVariable -- 现在 foo = nil.
aBoolValue = false aBoolValue = false
--只有nil和false为假; 0和 ''均为真! --只有nil和false为假; 0和 ''均为真!
if not aBoolValue then print('false') end if not aBoolValue then print('false') end
-- 'or'和 'and'短路 -- 'or'和 'and'短路
-- 类似于C/js里的 a?b:c 操作符: -- 类似于C/js里的 a?b:c 操作符:
ans = aBoolValue and 'yes' or 'no' --> 'no' ans = aBoolValue and 'yes' or 'no' --> 'no'
karlSum = 0 karlSum = 0
for i = 1, 100 do -- 范围包含两端 for i = 1, 100 do -- 范围包含两端
karlSum = karlSum + i karlSum = karlSum + i
end end
-- 使用 "100, 1, -1" 表示递减的范围: -- 使用 "100, 1, -1" 表示递减的范围:
fredSum = 0 fredSum = 0
for j = 100, 1, -1 do fredSum = fredSum + j end for j = 100, 1, -1 do fredSum = fredSum + j end
-- 通常范围表达式为begin, end[, step]. -- 通常范围表达式为begin, end[, step].
-- 循环的另一种结构: -- 循环的另一种结构:
repeat repeat
print('the way of the future') print('the way of the future')
num = num - 1 num = num - 1
until num == 0 until num == 0
---------------------------------------------------- ----------------------------------------------------
-- 2. 函数。 -- 2. 函数。
---------------------------------------------------- ----------------------------------------------------
function fib(n) function fib(n)
if n < 2 then return n end if n < 2 then return n end
return fib(n - 2) + fib(n - 1) return fib(n - 2) + fib(n - 1)
end end
-- 支持闭包及匿名函数: -- 支持闭包及匿名函数:
function adder(x) function adder(x)
-- 调用adder时会创建返回的函数 -- 调用adder时会创建返回的函数
-- 并且会记住x的值 -- 并且会记住x的值
return function (y) return x + y end return function (y) return x + y end
end end
a1 = adder(9) a1 = adder(9)
a2 = adder(36) a2 = adder(36)
print(a1(16)) --> 25 print(a1(16)) --> 25
print(a2(64)) --> 100 print(a2(64)) --> 100
-- 返回值、函数调用和赋值都可以 -- 返回值、函数调用和赋值都可以
-- 使用长度不匹配的list。 -- 使用长度不匹配的list。
-- 不匹配的接收方会被赋值nil -- 不匹配的接收方会被赋值nil
-- 不匹配的发送方会被丢弃。 -- 不匹配的发送方会被丢弃。
x, y, z = 1, 2, 3, 4 x, y, z = 1, 2, 3, 4
-- x = 1、y = 2、z = 3, 而 4 会被丢弃。 -- x = 1、y = 2、z = 3, 而 4 会被丢弃。
function bar(a, b, c) function bar(a, b, c)
print(a, b, c) print(a, b, c)
return 4, 8, 15, 16, 23, 42 return 4, 8, 15, 16, 23, 42
end end
x, y = bar('zaphod') --> 打印 "zaphod nil nil" x, y = bar('zaphod') --> 打印 "zaphod nil nil"
-- 现在 x = 4, y = 8, 而值15..42被丢弃。 -- 现在 x = 4, y = 8, 而值15..42被丢弃。
-- 函数是一等公民,可以是局部的,也可以是全局的。 -- 函数是一等公民,可以是局部的,也可以是全局的。
-- 以下表达式等价: -- 以下表达式等价:
function f(x) return x * x end function f(x) return x * x end
f = function (x) return x * x end f = function (x) return x * x end
-- 这些也是等价的: -- 这些也是等价的:
local function g(x) return math.sin(x) end local function g(x) return math.sin(x) end
local g; g = function (x) return math.sin(x) end local g; g = function (x) return math.sin(x) end
-- 以上均因'local g'使得g可以自引用。 -- 以上均因'local g'使得g可以自引用。
local g = function(x) return math.sin(x) end local g = function(x) return math.sin(x) end
-- 等价于 local function g(x)..., 但函数体中g不可自引用 -- 等价于 local function g(x)..., 但函数体中g不可自引用
-- 顺便提下,三角函数以弧度为单位。 -- 顺便提下,三角函数以弧度为单位。
-- 用一个字符串参数调用函数,可以省略括号: -- 用一个字符串参数调用函数,可以省略括号:
print 'hello' --可以工作。 print 'hello' --可以工作。
-- 调用函数时如果只有一个table参数 -- 调用函数时如果只有一个table参数
-- 同样可以省略括号table详情见下 -- 同样可以省略括号table详情见下
print {} -- 一样可以工作。 print {} -- 一样可以工作。
---------------------------------------------------- ----------------------------------------------------
-- 3. Table。 -- 3. Table。
---------------------------------------------------- ----------------------------------------------------
-- Table = Lua唯一的组合数据结构; -- Table = Lua唯一的组合数据结构;
-- 它们是关联数组。 -- 它们是关联数组。
-- 类似于PHP的数组或者js的对象 -- 类似于PHP的数组或者js的对象
-- 它们是哈希表或者字典,也可以当列表使用。 -- 它们是哈希表或者字典,也可以当列表使用。
-- 按字典/map的方式使用Table -- 按字典/map的方式使用Table
-- Dict字面量默认使用字符串类型的key -- Dict字面量默认使用字符串类型的key
t = {key1 = 'value1', key2 = false} t = {key1 = 'value1', key2 = false}
-- 字符串key可以使用类似js的点标记 -- 字符串key可以使用类似js的点标记
print(t.key1) -- 打印 'value1'. print(t.key1) -- 打印 'value1'.
t.newKey = {} -- 添加新的键值对。 t.newKey = {} -- 添加新的键值对。
t.key2 = nil -- 从table删除 key2。 t.key2 = nil -- 从table删除 key2。
-- 使用任何非nil的值作为key -- 使用任何非nil的值作为key
u = {['@!#'] = 'qbert', [{}] = 1729, [6.28] = 'tau'} u = {['@!#'] = 'qbert', [{}] = 1729, [6.28] = 'tau'}
print(u[6.28]) -- 打印 "tau" print(u[6.28]) -- 打印 "tau"
-- 数字和字符串的key按值匹配的 -- 数字和字符串的key按值匹配的
-- table按id匹配。 -- table按id匹配。
a = u['@!#'] -- 现在 a = 'qbert'. a = u['@!#'] -- 现在 a = 'qbert'.
b = u[{}] -- 我们或许期待的是 1729, 但是得到的是nil: b = u[{}] -- 我们或许期待的是 1729, 但是得到的是nil:
-- b = nil ,因为没有找到。 -- b = nil ,因为没有找到。
-- 之所以没找到是因为我们用的key与保存数据时用的不是同 -- 之所以没找到是因为我们用的key与保存数据时用的不是同
-- 一个对象。 -- 一个对象。
-- 所以字符串和数字是移植性更好的key。 -- 所以字符串和数字是移植性更好的key。
-- 只需要一个table参数的函数调用不需要括号 -- 只需要一个table参数的函数调用不需要括号
function h(x) print(x.key1) end function h(x) print(x.key1) end
h{key1 = 'Sonmi~451'} -- 打印'Sonmi~451'. h{key1 = 'Sonmi~451'} -- 打印'Sonmi~451'.
for key, val in pairs(u) do -- 遍历Table for key, val in pairs(u) do -- 遍历Table
print(key, val) 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 end
-- 'list'并非真正的类型v 其实是一个table
-- 只不过它用连续的整数作为key可以像list那样去使用。
---------------------------------------------------- -- _G 是一个特殊的table用于保存所有的全局变量
-- 3.1 元表metatable 和元方法metamethod 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的元表提供了一种机制支持类似操作符重载的行为。 -- table的元表提供了一种机制支持类似操作符重载的行为。
-- 稍后我们会看到元表如何支持类似js prototype的行为。 -- 稍后我们会看到元表如何支持类似js prototype的行为。
f1 = {a = 1, b = 2} -- 表示一个分数 a/b. f1 = {a = 1, b = 2} -- 表示一个分数 a/b.
f2 = {a = 2, b = 3} f2 = {a = 2, b = 3}
-- 这会失败: -- 这会失败:
-- s = f1 + f2 -- s = f1 + f2
metafraction = {} metafraction = {}
function metafraction.__add(f1, f2) function metafraction.__add(f1, f2)
local sum = {} local sum = {}
sum.b = f1.b * f2.b sum.b = f1.b * f2.b
sum.a = f1.a * f2.b + f2.a * f1.b sum.a = f1.a * f2.b + f2.a * f1.b
return sum return sum
end end
setmetatable(f1, metafraction) setmetatable(f1, metafraction)
setmetatable(f2, metafraction) setmetatable(f2, metafraction)
s = f1 + f2 -- 调用在f1的元表上的__add(f1, f2) 方法 s = f1 + f2 -- 调用在f1的元表上的__add(f1, f2) 方法
-- f1, f2 没有关于元表的key这点和js的prototype不一样。 -- f1, f2 没有关于元表的key这点和js的prototype不一样。
-- 因此你必须用getmetatable(f1)获取元表。 -- 因此你必须用getmetatable(f1)获取元表。
-- 元表是一个普通的table -- 元表是一个普通的table
-- 元表的key是普通的Lua中的key例如__add。 -- 元表的key是普通的Lua中的key例如__add。
-- 但是下面一行代码会失败因为s没有元表 -- 但是下面一行代码会失败因为s没有元表
-- t = s + s -- t = s + s
-- 下面提供的与类相似的模式可以解决这个问题: -- 下面提供的与类相似的模式可以解决这个问题:
-- 元表的__index 可以重载用于查找的点操作符: -- 元表的__index 可以重载用于查找的点操作符:
defaultFavs = {animal = 'gru', food = 'donuts'} defaultFavs = {animal = 'gru', food = 'donuts'}
myFavs = {food = 'pizza'} myFavs = {food = 'pizza'}
setmetatable(myFavs, {__index = defaultFavs}) setmetatable(myFavs, {__index = defaultFavs})
eatenBy = myFavs.animal -- 可以工作!感谢元表 eatenBy = myFavs.animal -- 可以工作!感谢元表
-- 如果在table中直接查找key失败会使用 -- 如果在table中直接查找key失败会使用
-- 元表的__index 递归地重试。 -- 元表的__index 递归地重试。
-- __index的值也可以是function(tbl, key) -- __index的值也可以是function(tbl, key)
-- 这样可以支持自定义查找。 -- 这样可以支持自定义查找。
-- __index、__add等的值被称为元方法。 -- __index、__add等的值被称为元方法。
-- 这里是一个table元方法的清单 -- 这里是一个table元方法的清单
-- __add(a, b) for a + b -- __add(a, b) for a + b
-- __sub(a, b) for a - b -- __sub(a, b) for a - b
-- __mul(a, b) for a * b -- __mul(a, b) for a * b
-- __div(a, b) for a / b -- __div(a, b) for a / b
-- __mod(a, b) for a % b -- __mod(a, b) for a % b
-- __pow(a, b) for a ^ b -- __pow(a, b) for a ^ b
-- __unm(a) for -a -- __unm(a) for -a
-- __concat(a, b) for a .. b -- __concat(a, b) for a .. b
-- __len(a) for #a -- __len(a) for #a
-- __eq(a, b) for a == b -- __eq(a, b) for a == b
-- __lt(a, b) for a < b -- __lt(a, b) for a < b
-- __le(a, b) for a <= b -- __le(a, b) for a <= b
-- __index(a, b) <fn or a table> for a.b -- __index(a, b) <fn or a table> for a.b
-- __newindex(a, b, c) for a.b = c -- __newindex(a, b, c) for a.b = c
-- __call(a, ...) for a(...) -- __call(a, ...) for a(...)
---------------------------------------------------- ----------------------------------------------------
-- 3.2 与类相似的table和继承。 -- 3.2 与类相似的table和继承。
---------------------------------------------------- ----------------------------------------------------
-- Lua没有内建的类可以通过不同的方法利用表和元表 -- Lua没有内建的类可以通过不同的方法利用表和元表
-- 来实现类。 -- 来实现类。
-- 下面是一个例子,解释在后面: -- 下面是一个例子,解释在后面:
Dog = {} -- 1. Dog = {} -- 1.
function Dog:new() -- 2. function Dog:new() -- 2.
local newObj = {sound = 'woof'} -- 3. local newObj = {sound = 'woof'} -- 3.
self.__index = self -- 4. self.__index = self -- 4.
return setmetatable(newObj, self) -- 5. return setmetatable(newObj, self) -- 5.
end end
function Dog:makeSound() -- 6. function Dog:makeSound() -- 6.
print('I say ' .. self.sound) print('I say ' .. self.sound)
end end
mrDog = Dog:new() -- 7. mrDog = Dog:new() -- 7.
mrDog:makeSound() -- 'I say woof' -- 8. mrDog:makeSound() -- 'I say woof' -- 8.
-- 1. Dog看上去像一个类其实它是一个table。 -- 1. Dog看上去像一个类其实它是一个table。
-- 2. 函数tablename:fn(...) 等价于 -- 2. 函数tablename:fn(...) 等价于
-- 函数tablename.fn(self, ...) -- 函数tablename.fn(self, ...)
-- 冒号(:只是添加了self作为第一个参数。 -- 冒号(:只是添加了self作为第一个参数。
-- 阅读7 & 8条 了解self变量是如何得到其值的。 -- 阅读7 & 8条 了解self变量是如何得到其值的。
-- 3. newObj是类Dog的一个实例。 -- 3. newObj是类Dog的一个实例。
-- 4. self = 被继承的类。通常self = Dog不过继承可以改变它。 -- 4. self = 被继承的类。通常self = Dog不过继承可以改变它。
-- 如果把newObj的元表和__index都设置为self -- 如果把newObj的元表和__index都设置为self
-- newObj就可以得到self的函数。 -- newObj就可以得到self的函数。
-- 5. 备忘setmetatable返回其第一个参数。 -- 5. 备忘setmetatable返回其第一个参数。
-- 6. 冒号的作用和第2条一样不过这里 -- 6. 冒号的作用和第2条一样不过这里
-- self是一个实例而不是类 -- self是一个实例而不是类
-- 7. 等价于Dog.new(Dog)所以在new()中self = Dog。 -- 7. 等价于Dog.new(Dog)所以在new()中self = Dog。
-- 8. 等价于mrDog.makeSound(mrDog); self = mrDog。 -- 8. 等价于mrDog.makeSound(mrDog); self = mrDog。
---------------------------------------------------- ----------------------------------------------------
-- 继承的例子: -- 继承的例子:
LoudDog = Dog:new() -- 1. LoudDog = Dog:new() -- 1.
function LoudDog:makeSound() function LoudDog:makeSound()
local s = self.sound .. ' ' -- 2. local s = self.sound .. ' ' -- 2.
print(s .. s .. s) print(s .. s .. s)
end end
seymour = LoudDog:new() -- 3. seymour = LoudDog:new() -- 3.
seymour:makeSound() -- 'woof woof woof' -- 4. seymour:makeSound() -- 'woof woof woof' -- 4.
-- 1. LoudDog获得Dog的方法和变量列表。 -- 1. LoudDog获得Dog的方法和变量列表。
-- 2. 因为new()的缘故self拥有了一个'sound' key参见第3条。 -- 2. 因为new()的缘故self拥有了一个'sound' key参见第3条。
-- 3. 等价于LoudDog.new(LoudDog),转换一下就是 -- 3. 等价于LoudDog.new(LoudDog),转换一下就是
-- Dog.new(LoudDog)这是因为LoudDog没有'new' key -- Dog.new(LoudDog)这是因为LoudDog没有'new' key
-- 但是它的元表中有 __index = Dog。 -- 但是它的元表中有 __index = Dog。
-- 结果: seymour的元表是LoudDog并且 -- 结果: seymour的元表是LoudDog并且
-- LoudDog.__index = Dog。所以有seymour.key -- LoudDog.__index = Dog。所以有seymour.key
-- = seymour.key, LoudDog.key, Dog.key -- = seymour.key, LoudDog.key, Dog.key
-- 从其中第一个有指定key的table获取。 -- 从其中第一个有指定key的table获取。
-- 4. 在LoudDog可以找到'makeSound'的key -- 4. 在LoudDog可以找到'makeSound'的key
-- 等价于LoudDog.makeSound(seymour)。 -- 等价于LoudDog.makeSound(seymour)。
-- 如果有必要子类也可以有new(),与基类相似: -- 如果有必要子类也可以有new(),与基类相似:
function LoudDog:new() function LoudDog:new()
local newObj = {} local newObj = {}
-- 初始化newObj -- 初始化newObj
self.__index = self self.__index = self
return setmetatable(newObj, self) return setmetatable(newObj, self)
end end
---------------------------------------------------- ----------------------------------------------------
-- 4. 模块 -- 4. 模块
---------------------------------------------------- ----------------------------------------------------
--[[ 我把这部分给注释了,这样脚本剩下的部分可以运行 --[[ 我把这部分给注释了,这样脚本剩下的部分可以运行
``` ```
```lua ```lua
-- 假设文件mod.lua的内容类似这样 -- 假设文件mod.lua的内容类似这样
local M = {} local M = {}
local function sayMyName() local function sayMyName()
print('Hrunkner') print('Hrunkner')
end end
function M.sayHello() function M.sayHello()
print('Why hello there') print('Why hello there')
sayMyName() sayMyName()
end end
return M return M
-- 另一个文件可以使用mod.lua的功能 -- 另一个文件可以使用mod.lua的功能
local mod = require('mod') -- 运行文件mod.lua. local mod = require('mod') -- 运行文件mod.lua.
-- 注意require 需要配合 LUA_PATH 一起使用 例如export LUA_PATH="$HOME/workspace/projectName/?.lua;;" -- 注意require 需要配合 LUA_PATH 一起使用 例如export LUA_PATH="$HOME/workspace/projectName/?.lua;;"
-- require是包含模块的标准做法。 -- require是包含模块的标准做法。
-- require等价于: (针对没有被缓存的情况;参见后面的内容) -- require等价于: (针对没有被缓存的情况;参见后面的内容)
local mod = (function () local mod = (function ()
<contents of mod.lua> <contents of mod.lua>
end)() end)()
-- mod.lua被包在一个函数体中因此mod.lua的局部变量 -- mod.lua被包在一个函数体中因此mod.lua的局部变量
-- 对外不可见。 -- 对外不可见。
-- 下面的代码可以工作因为在这里mod = mod.lua 中的 M -- 下面的代码可以工作因为在这里mod = mod.lua 中的 M
mod.sayHello() -- Says hello to Hrunkner. mod.sayHello() -- Says hello to Hrunkner.
-- 这是错误的sayMyName只在mod.lua中存在 -- 这是错误的sayMyName只在mod.lua中存在
mod.sayMyName() -- 错误 mod.sayMyName() -- 错误
-- require返回的值会被缓存所以一个文件只会被运行一次 -- require返回的值会被缓存所以一个文件只会被运行一次
-- 即使它被require了多次。 -- 即使它被require了多次。
-- 假设mod2.lua包含代码"print('Hi!')"。 -- 假设mod2.lua包含代码"print('Hi!')"。
local a = require('mod2') -- 打印Hi! local a = require('mod2') -- 打印Hi!
local b = require('mod2') -- 不再打印; a=b. local b = require('mod2') -- 不再打印; a=b.
-- dofile与require类似但是不缓存 -- dofile与require类似但是不缓存
dofile('mod2') --> Hi! dofile('mod2') --> Hi!
dofile('mod2') --> Hi! (再次运行与require不同) dofile('mod2') --> Hi! (再次运行与require不同)
-- loadfile加载一个lua文件但是并不运行它。 -- loadfile加载一个lua文件但是并不运行它。
f = loadfile('mod2') -- Calling f() runs mod2.lua. f = loadfile('mod2') -- Calling f() runs mod2.lua.
-- loadstring是loadfile的字符串版本。 -- loadstring是loadfile的字符串版本。
-- (loadstring已弃用, 使用load代替) -- (loadstring已弃用, 使用load代替)
g = load('print(343)') --返回一个函数。 g = load('print(343)') --返回一个函数。
g() -- 打印343; 在此之前什么也不打印。 g() -- 打印343; 在此之前什么也不打印。
--]] --]]
``` ```
## 参考 ## 参考
为什么我非常兴奋地学习lua 这样我就可以使用[LÖVE 2D游戏引擎](http://love2d.org/)来编游戏。
为什么我非常兴奋地学习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)一书。 怎么做?我从[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)应该值得一看。 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; * [`string` library](http://lua-users.org/wiki/StringLibraryTutorial)
* [`table` library](http://lua-users.org/wiki/TableLibraryTutorial)
* [`math` library](http://lua-users.org/wiki/MathLibraryTutorial)
* [`io` library](http://lua-users.org/wiki/IoLibraryTutorial)
* [`os` library](http://lua-users.org/wiki/OsLibraryTutorial)
顺便说一下整个文件是可运行的Lua;
保存为 learn-cn.lua 用命令 `lua learn-cn.lua` 启动吧! 保存为 learn-cn.lua 用命令 `lua learn-cn.lua` 启动吧!
本文首次撰写于 [tylerneylon.com](http://tylerneylon.com) 同时也有 [GitHub gist](https://gist.github.com/tylerneylon/5853042) 版. 本文首次撰写于 [tylerneylon.com](http://tylerneylon.com) 同时也有 [GitHub gist](https://gist.github.com/tylerneylon/5853042) 版.