mirror of
https://github.com/adambard/learnxinyminutes-docs.git
synced 2025-08-17 20:11:57 +02:00
Merge remote-tracking branch 'upstream/master'
This commit is contained in:
@@ -6,6 +6,7 @@ contributors:
|
|||||||
- ["Sonia Keys", "https://github.com/soniakeys"]
|
- ["Sonia Keys", "https://github.com/soniakeys"]
|
||||||
translators:
|
translators:
|
||||||
- ["Szabó Krisztián", "https://github.com/thenonameguy/"]
|
- ["Szabó Krisztián", "https://github.com/thenonameguy/"]
|
||||||
|
- ["Árpád Goretity", "https://github.com/H2CO3"]
|
||||||
---
|
---
|
||||||
|
|
||||||
A Go programozási nyelv az életszerű feladatok könnyebb elvégzése miatt született.
|
A Go programozási nyelv az életszerű feladatok könnyebb elvégzése miatt született.
|
||||||
@@ -38,14 +39,14 @@ import (
|
|||||||
"strconv" // Stringek átalakítására szolgáló csomag
|
"strconv" // Stringek átalakítására szolgáló csomag
|
||||||
)
|
)
|
||||||
|
|
||||||
// Funkció deklarálás, a main nevű funkció a program kezdőpontja.
|
// Függvénydeklarálás, a main nevű függvény a program kezdőpontja.
|
||||||
func main() {
|
func main() {
|
||||||
// Println kiírja a beadott paramétereket a standard kimenetre.
|
// Println kiírja a beadott paramétereket a standard kimenetre.
|
||||||
// Ha más csomagot funkcióját akarjuk használni, akkor azt jelezni kell a
|
// Ha más csomagot függvényeit akarjuk használni, akkor azt jelezni kell a
|
||||||
// csomag nevével
|
// csomag nevével
|
||||||
fmt.Println("Hello world!")
|
fmt.Println("Hello world!")
|
||||||
|
|
||||||
// Meghívunk egy másik funkciót ebből a csomagból
|
// Meghívunk egy másik függvényt ebből a csomagból
|
||||||
beyondHello()
|
beyondHello()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -92,7 +93,7 @@ func learnTypes() {
|
|||||||
// lebegőpontos szám
|
// lebegőpontos szám
|
||||||
c := 3 + 4i // complex128, belsőleg két float64-gyel tárolva
|
c := 3 + 4i // complex128, belsőleg két float64-gyel tárolva
|
||||||
|
|
||||||
// Var szintaxis változó típus definiálással
|
// Var szintaxis változótípus-definiálással
|
||||||
var u uint = 7 // unsigned, az implementáció dönti el mekkora, akárcsak az
|
var u uint = 7 // unsigned, az implementáció dönti el mekkora, akárcsak az
|
||||||
// int-nél
|
// int-nél
|
||||||
var pi float32 = 22. / 7
|
var pi float32 = 22. / 7
|
||||||
@@ -105,8 +106,8 @@ func learnTypes() {
|
|||||||
a3 := [...]int{3, 1, 5} // egy tömb 3 int-tel, láthatóan inicalizálva egyedi
|
a3 := [...]int{3, 1, 5} // egy tömb 3 int-tel, láthatóan inicalizálva egyedi
|
||||||
// értékekre
|
// értékekre
|
||||||
|
|
||||||
// Szeleteknek dinamikus a méretük. A szeleteknek és a tömböknek is meg
|
// A "szeleteknek" (slices) dinamikus a méretük. A szeleteknek és a tömböknek is
|
||||||
// vannak az előnyeik de a szeleteket sokkal gyakrabban használjuk.
|
// megvannak az előnyeik de a szeleteket sokkal gyakrabban használjuk.
|
||||||
s3 := []int{4, 5, 9} // vesd össze a3-mal, nincsenek pontok.
|
s3 := []int{4, 5, 9} // vesd össze a3-mal, nincsenek pontok.
|
||||||
s4 := make([]int, 4) // allokál 4 int-et, mind 0-ra inicializálva
|
s4 := make([]int, 4) // allokál 4 int-et, mind 0-ra inicializálva
|
||||||
var d2 [][]float64 // ez csak deklaráció, semmi sincs még allokálva
|
var d2 [][]float64 // ez csak deklaráció, semmi sincs még allokálva
|
||||||
@@ -129,8 +130,8 @@ func learnTypes() {
|
|||||||
learnFlowControl()
|
learnFlowControl()
|
||||||
}
|
}
|
||||||
|
|
||||||
// A Go nyelv teljesen szemétgyűjtött (garbage-collected). Megtalálhatók benne
|
// A Go nyelvben szemétgyűjtés (garbage collection) működik. Megtalálhatók benne
|
||||||
// mutatók, de nincs mutató aritmetika. Ez azt jelenti, hogy üres mutatóval még
|
// mutatók, de nincs pointeraritmetika. Ez azt jelenti, hogy üres (null) mutatóval még
|
||||||
// mindig hibázhatsz, de hozzáadni/műveleteket végezni már nem lehet.
|
// mindig hibázhatsz, de hozzáadni/műveleteket végezni már nem lehet.
|
||||||
func learnMemory() (p, q *int) {
|
func learnMemory() (p, q *int) {
|
||||||
// Elnevezett visszatérési változóknak int-re mutató a típusa
|
// Elnevezett visszatérési változóknak int-re mutató a típusa
|
||||||
@@ -213,7 +214,7 @@ type pair struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Definiáljunk egy metódust a pair struktúrának, ezzel teljesítve a Stringer interfészt.
|
// Definiáljunk egy metódust a pair struktúrának, ezzel teljesítve a Stringer interfészt.
|
||||||
func (p pair) String() string { // p lesz a "vevő"
|
func (p pair) String() string { // p lesz a "fogadó" (receiver)
|
||||||
// Sprintf az fmt csomag egy publikus függvénye, műkődése megegyezik a C-s
|
// Sprintf az fmt csomag egy publikus függvénye, műkődése megegyezik a C-s
|
||||||
// megfelelőjével. A pontokkal érjük el a mindenkori p struktúra elemeit
|
// megfelelőjével. A pontokkal érjük el a mindenkori p struktúra elemeit
|
||||||
return fmt.Sprintf("(%d, %d)", p.x, p.y)
|
return fmt.Sprintf("(%d, %d)", p.x, p.y)
|
||||||
@@ -230,7 +231,7 @@ func learnInterfaces() {
|
|||||||
// Meghívjuk i String metódusát, az eredmény ugyanaz, mint az előbb.
|
// Meghívjuk i String metódusát, az eredmény ugyanaz, mint az előbb.
|
||||||
fmt.Println(i.String())
|
fmt.Println(i.String())
|
||||||
|
|
||||||
// Az fmt csomag funckciói automatikusan meghívják a String funkciót
|
// Az fmt csomag függvényei automatikusan meghívják a String függvényt
|
||||||
// hogy megtudják egy objektum szöveges reprezentációját.
|
// hogy megtudják egy objektum szöveges reprezentációját.
|
||||||
fmt.Println(p) // ugyan az az eredmény mint az előbb, a Println meghívja
|
fmt.Println(p) // ugyan az az eredmény mint az előbb, a Println meghívja
|
||||||
// a String metódust.
|
// a String metódust.
|
||||||
@@ -267,8 +268,8 @@ func inc(i int, c chan int) {
|
|||||||
|
|
||||||
// Az inc-et fogjuk arra használni, hogy konkurensen megnöveljünk számokat
|
// Az inc-et fogjuk arra használni, hogy konkurensen megnöveljünk számokat
|
||||||
func learnConcurrency() {
|
func learnConcurrency() {
|
||||||
// Ugyan az a make funkció amivel korábban szeleteket hoztunk létre.
|
// Ugyanaz a make függvény, amivel korábban szeleteket hoztunk létre.
|
||||||
// Make allokál mapokat, szeleteket és csatornákat.
|
// A make allokál map-eket, szeleteket és csatornákat.
|
||||||
c := make(chan int)
|
c := make(chan int)
|
||||||
// Indítsunk három konkurens goroutine-t. A számok konkurensen lesznek
|
// Indítsunk három konkurens goroutine-t. A számok konkurensen lesznek
|
||||||
// megnövelve, ha a számítógép képes rá és jól be van állítva, akkor pedig
|
// megnövelve, ha a számítógép képes rá és jól be van állítva, akkor pedig
|
||||||
@@ -299,14 +300,14 @@ func learnConcurrency() {
|
|||||||
case <-cc: // üres csatorna, soha nem fog rajta semmi se érkezni
|
case <-cc: // üres csatorna, soha nem fog rajta semmi se érkezni
|
||||||
fmt.Println("sose futok le :'( ")
|
fmt.Println("sose futok le :'( ")
|
||||||
}
|
}
|
||||||
// Ezen a ponton vagy c vagy a cs goroutineja lefutott.
|
// Ezen a ponton vagy c vagy a cs goroutine-ja lefutott.
|
||||||
// Amelyik hamarabb végzett, annak a megfelelő case-e lefutott, a másik
|
// Amelyik hamarabb végzett, annak a megfelelő case-e lefutott, a másik
|
||||||
// blokkolva vár.
|
// blokkolva vár.
|
||||||
|
|
||||||
learnWebProgramming() // Go képes rá. Te is képes akarsz rá lenni.
|
learnWebProgramming() // a Go képes rá. Te is képes akarsz rá lenni.
|
||||||
}
|
}
|
||||||
|
|
||||||
// Egy funkció a http csomagból elindít egy webszervert.
|
// Egy függvény a http csomagból elindít egy webszervert.
|
||||||
func learnWebProgramming() {
|
func learnWebProgramming() {
|
||||||
// A ListenAndServe első paramétre egy TCP port, amin kiszolgálunk majd.
|
// A ListenAndServe első paramétre egy TCP port, amin kiszolgálunk majd.
|
||||||
// Második paramétere egy interfész, pontosabban a http.Handler interfész.
|
// Második paramétere egy interfész, pontosabban a http.Handler interfész.
|
||||||
@@ -315,7 +316,7 @@ func learnWebProgramming() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Csináljunk a pair-ból egy http.Handler-t úgy, hogy implementáljuk az
|
// Csináljunk a pair-ból egy http.Handler-t úgy, hogy implementáljuk az
|
||||||
// egyetlen metódusát a ServeHTTP-t.
|
// egyetlen metódusát, a ServeHTTP-t.
|
||||||
func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||||
// Minden kapcsolatra elküldjük ezt a http.ResponseWriter-rel
|
// Minden kapcsolatra elküldjük ezt a http.ResponseWriter-rel
|
||||||
w.Write([]byte("Megtanultad a Go-t Y perc alatt!"))
|
w.Write([]byte("Megtanultad a Go-t Y perc alatt!"))
|
||||||
@@ -325,11 +326,12 @@ func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|||||||
## További olvasmányok
|
## További olvasmányok
|
||||||
|
|
||||||
Minden Go-val kapcsolatos megtaláható a [hivatalos Go weboldalon](http://golang.org/).
|
Minden Go-val kapcsolatos megtaláható a [hivatalos Go weboldalon](http://golang.org/).
|
||||||
Ott követhetsz egy tutorialt, játszhatsz a nyelvvel az interneten és sok érdekességet olvashatsz.
|
Ott követhetsz egy tutorialt, játszhatsz a nyelvvel az interneten, és sok érdekességet olvashatsz.
|
||||||
|
|
||||||
A nyelv specifikációját kifejezetten érdemes olvasni, viszonylag rövid és sokat tanul belőle az ember.
|
A nyelv specifikációját kifejezetten érdemes olvasni, viszonylag rövid és sokat tanul belőle az ember.
|
||||||
|
|
||||||
Ha pedig jobban bele akarod vetni magad a Go-ba, akkor a standard könyvtárban a legjobb praktikákat kilesheted.
|
Ha pedig jobban bele akarod vetni magad a Go-ba, akkor a legjobb praktikákat kilesheted a standard könyvtárból.
|
||||||
TIPP: a dokumentációban kattints egy funkció nevére és rögtön megmutatja a hozzá tartozó kódot!
|
TIPP: a dokumentációban kattints egy függvény nevére és rögtön megmutatja a hozzá tartozó kódot!
|
||||||
|
|
||||||
Ha pedig a nyelvnek egy bizonyos részéről szeretnél hasonló leírást találni, akkor a [gobyexample.com](https://gobyexample.com/)-on megtalálod, amit keresel.
|
Ha pedig a nyelvnek egy bizonyos részéről szeretnél hasonló leírást találni, akkor a
|
||||||
|
[gobyexample.com](https://gobyexample.com/)-on megtalálod, amit keresel.
|
||||||
|
@@ -215,7 +215,7 @@ dan susunan markup:
|
|||||||
```
|
```
|
||||||
|
|
||||||
Maka prioritas penerapan style-nya ialah sbb.:
|
Maka prioritas penerapan style-nya ialah sbb.:
|
||||||
Ingat, penerapan ini untuk masing-masing properti **property**,
|
Ingat, penerapan ini untuk masing-masing **properti**,
|
||||||
bukan keseluruhan larik.
|
bukan keseluruhan larik.
|
||||||
|
|
||||||
* `E` prioritas pertama sebab ada kata `!important`.
|
* `E` prioritas pertama sebab ada kata `!important`.
|
||||||
|
@@ -12,15 +12,13 @@ filename: learnlua.lua
|
|||||||
Adding two ['s and ]'s makes it a
|
Adding two ['s and ]'s makes it a
|
||||||
multi-line comment.
|
multi-line comment.
|
||||||
--]]
|
--]]
|
||||||
|
--------------------------------------------------------------------------------
|
||||||
----------------------------------------------------
|
|
||||||
-- 1. Variables and flow control.
|
-- 1. Variables and flow control.
|
||||||
----------------------------------------------------
|
--------------------------------------------------------------------------------
|
||||||
|
|
||||||
num = 42 -- All numbers are doubles.
|
num = 42 -- All numbers are doubles.
|
||||||
-- Don't freak out, 64-bit doubles have 52 bits for
|
-- Don't freak out, 64-bit doubles have 52 bits for storing exact int
|
||||||
-- storing exact int values; machine precision is
|
-- values; machine precision is not a problem for ints that need < 52 bits.
|
||||||
-- not a problem for ints that need < 52 bits.
|
|
||||||
|
|
||||||
s = 'walternate' -- Immutable strings like Python.
|
s = 'walternate' -- Immutable strings like Python.
|
||||||
t = "double-quotes are also fine"
|
t = "double-quotes are also fine"
|
||||||
@@ -60,8 +58,8 @@ aBoolValue = false
|
|||||||
-- Only nil and false are falsy; 0 and '' are true!
|
-- Only nil and false are falsy; 0 and '' are true!
|
||||||
if not aBoolValue then print('twas false') end
|
if not aBoolValue then print('twas false') end
|
||||||
|
|
||||||
-- 'or' and 'and' are short-circuited.
|
-- 'or' and 'and' are short-circuited. This is similar to the a?b:c operator
|
||||||
-- This is similar to the a?b:c operator in C/js:
|
-- in C/js:
|
||||||
ans = aBoolValue and 'yes' or 'no' --> 'no'
|
ans = aBoolValue and 'yes' or 'no' --> 'no'
|
||||||
|
|
||||||
karlSum = 0
|
karlSum = 0
|
||||||
@@ -81,10 +79,9 @@ repeat
|
|||||||
num = num - 1
|
num = num - 1
|
||||||
until num == 0
|
until num == 0
|
||||||
|
|
||||||
|
--------------------------------------------------------------------------------
|
||||||
----------------------------------------------------
|
|
||||||
-- 2. Functions.
|
-- 2. Functions.
|
||||||
----------------------------------------------------
|
--------------------------------------------------------------------------------
|
||||||
|
|
||||||
function fib(n)
|
function fib(n)
|
||||||
if n < 2 then return n end
|
if n < 2 then return n end
|
||||||
@@ -93,8 +90,8 @@ end
|
|||||||
|
|
||||||
-- Closures and anonymous functions are ok:
|
-- Closures and anonymous functions are ok:
|
||||||
function adder(x)
|
function adder(x)
|
||||||
-- The returned function is created when adder is
|
-- The returned function is created when adder is called, and remembers the
|
||||||
-- called, and remembers the value of x:
|
-- value of x:
|
||||||
return function (y) return x + y end
|
return function (y) return x + y end
|
||||||
end
|
end
|
||||||
a1 = adder(9)
|
a1 = adder(9)
|
||||||
@@ -102,10 +99,9 @@ a2 = adder(36)
|
|||||||
print(a1(16)) --> 25
|
print(a1(16)) --> 25
|
||||||
print(a2(64)) --> 100
|
print(a2(64)) --> 100
|
||||||
|
|
||||||
-- Returns, func calls, and assignments all work
|
-- Returns, func calls, and assignments all work with lists that may be
|
||||||
-- with lists that may be mismatched in length.
|
-- mismatched in length. Unmatched receivers are nil; unmatched senders are
|
||||||
-- Unmatched receivers are nil;
|
-- discarded.
|
||||||
-- unmatched senders are discarded.
|
|
||||||
|
|
||||||
x, y, z = 1, 2, 3, 4
|
x, y, z = 1, 2, 3, 4
|
||||||
-- Now x = 1, y = 2, z = 3, and 4 is thrown away.
|
-- Now x = 1, y = 2, z = 3, and 4 is thrown away.
|
||||||
@@ -118,16 +114,15 @@ end
|
|||||||
x, y = bar('zaphod') --> prints "zaphod nil nil"
|
x, y = bar('zaphod') --> prints "zaphod nil nil"
|
||||||
-- Now x = 4, y = 8, values 15..42 are discarded.
|
-- Now x = 4, y = 8, values 15..42 are discarded.
|
||||||
|
|
||||||
-- Functions are first-class, may be local/global.
|
-- Functions are first-class, may be local/global. These are the same:
|
||||||
-- These are the same:
|
|
||||||
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
|
||||||
|
|
||||||
-- And so are these:
|
-- And so are these:
|
||||||
local function g(x) return math.sin(x) end
|
local function g(x) return math.sin(x) end
|
||||||
local g = function(x) return math.sin(x) end
|
local g = function(x) return math.sin(x) end
|
||||||
-- Equivalent to local function g(x)..., except referring
|
-- Equivalent to local function g(x)..., except referring to g in the function
|
||||||
-- to g in the function body won't work as expected.
|
-- body won't work as expected.
|
||||||
local g; g = function (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.
|
-- the 'local g' decl makes g-self-references ok.
|
||||||
|
|
||||||
@@ -136,19 +131,16 @@ local g; g = function (x) return math.sin(x) end
|
|||||||
-- Calls with one string param don't need parens:
|
-- Calls with one string param don't need parens:
|
||||||
print 'hello' -- Works fine.
|
print 'hello' -- Works fine.
|
||||||
|
|
||||||
-- Calls with one table param don't need parens
|
-- Calls with one table param don't need parens either (more on tables below):
|
||||||
-- either (more on tables below):
|
|
||||||
print {} -- Works fine too.
|
print {} -- Works fine too.
|
||||||
|
|
||||||
|
--------------------------------------------------------------------------------
|
||||||
----------------------------------------------------
|
|
||||||
-- 3. Tables.
|
-- 3. Tables.
|
||||||
----------------------------------------------------
|
--------------------------------------------------------------------------------
|
||||||
|
|
||||||
-- Tables = Lua's only compound data structure;
|
-- Tables = Lua's only compound data structure; they are associative arrays.
|
||||||
-- they are associative arrays.
|
-- Similar to php arrays or js objects, they are hash-lookup dicts that can
|
||||||
-- Similar to php arrays or js objects, they are
|
-- also be used as lists.
|
||||||
-- hash-lookup dicts that can also be used as lists.
|
|
||||||
|
|
||||||
-- Using tables as dictionaries / maps:
|
-- Using tables as dictionaries / maps:
|
||||||
|
|
||||||
@@ -164,14 +156,13 @@ t.key2 = nil -- Removes key2 from the table.
|
|||||||
u = {['@!#'] = 'qbert', [{}] = 1729, [6.28] = 'tau'}
|
u = {['@!#'] = 'qbert', [{}] = 1729, [6.28] = 'tau'}
|
||||||
print(u[6.28]) -- prints "tau"
|
print(u[6.28]) -- prints "tau"
|
||||||
|
|
||||||
-- Key matching is basically by value for numbers
|
-- Key matching is basically by value for numbers and strings, but by identity
|
||||||
-- and strings, but by identity for tables.
|
-- for tables.
|
||||||
a = u['@!#'] -- Now a = 'qbert'.
|
a = u['@!#'] -- Now a = 'qbert'.
|
||||||
b = u[{}] -- We might expect 1729, but it's nil:
|
b = u[{}] -- We might expect 1729, but it's nil:
|
||||||
-- b = nil since the lookup fails. It fails
|
-- b = nil since the lookup fails. It fails because the key we used is not the
|
||||||
-- because the key we used is not the same object
|
-- same object as the one used to store the original value. So strings &
|
||||||
-- as the one used to store the original value. So
|
-- numbers are more portable keys.
|
||||||
-- strings & numbers are more portable keys.
|
|
||||||
|
|
||||||
-- A one-table-param function call needs no parens:
|
-- A one-table-param function call needs no parens:
|
||||||
function h(x) print(x.key1) end
|
function h(x) print(x.key1) end
|
||||||
@@ -191,16 +182,15 @@ v = {'value1', 'value2', 1.21, 'gigawatts'}
|
|||||||
for i = 1, #v do -- #v is the size of v for lists.
|
for i = 1, #v do -- #v is the size of v for lists.
|
||||||
print(v[i]) -- Indices start at 1 !! SO CRAZY!
|
print(v[i]) -- Indices start at 1 !! SO CRAZY!
|
||||||
end
|
end
|
||||||
-- A 'list' is not a real type. v is just a table
|
-- A 'list' is not a real type. v is just a table with consecutive integer
|
||||||
-- with consecutive integer keys, treated as a list.
|
-- keys, treated as a list.
|
||||||
|
|
||||||
----------------------------------------------------
|
--------------------------------------------------------------------------------
|
||||||
-- 3.1 Metatables and metamethods.
|
-- 3.1 Metatables and metamethods.
|
||||||
----------------------------------------------------
|
--------------------------------------------------------------------------------
|
||||||
|
|
||||||
-- A table can have a metatable that gives the table
|
-- A table can have a metatable that gives the table operator-overloadish
|
||||||
-- operator-overloadish behavior. Later we'll see
|
-- behavior. Later we'll see how metatables support js-prototypey behavior.
|
||||||
-- how metatables support js-prototypey behavior.
|
|
||||||
|
|
||||||
f1 = {a = 1, b = 2} -- Represents the fraction a/b.
|
f1 = {a = 1, b = 2} -- Represents the fraction a/b.
|
||||||
f2 = {a = 2, b = 3}
|
f2 = {a = 2, b = 3}
|
||||||
@@ -221,10 +211,9 @@ setmetatable(f2, metafraction)
|
|||||||
|
|
||||||
s = f1 + f2 -- call __add(f1, f2) on f1's metatable
|
s = f1 + f2 -- call __add(f1, f2) on f1's metatable
|
||||||
|
|
||||||
-- f1, f2 have no key for their metatable, unlike
|
-- f1, f2 have no key for their metatable, unlike prototypes in js, so you must
|
||||||
-- prototypes in js, so you must retrieve it as in
|
-- retrieve it as in getmetatable(f1). The metatable is a normal table with
|
||||||
-- getmetatable(f1). The metatable is a normal table
|
-- keys that Lua knows about, like __add.
|
||||||
-- with keys that Lua knows about, like __add.
|
|
||||||
|
|
||||||
-- But the next line fails since s has no metatable:
|
-- But the next line fails since s has no metatable:
|
||||||
-- t = s + s
|
-- t = s + s
|
||||||
@@ -236,11 +225,12 @@ myFavs = {food = 'pizza'}
|
|||||||
setmetatable(myFavs, {__index = defaultFavs})
|
setmetatable(myFavs, {__index = defaultFavs})
|
||||||
eatenBy = myFavs.animal -- works! thanks, metatable
|
eatenBy = myFavs.animal -- works! thanks, metatable
|
||||||
|
|
||||||
-- Direct table lookups that fail will retry using
|
--------------------------------------------------------------------------------
|
||||||
-- the metatable's __index value, and this recurses.
|
-- Direct table lookups that fail will retry using the metatable's __index
|
||||||
|
-- value, and this recurses.
|
||||||
|
|
||||||
-- An __index value can also be a function(tbl, key)
|
-- An __index value can also be a function(tbl, key) for more customized
|
||||||
-- for more customized lookups.
|
-- lookups.
|
||||||
|
|
||||||
-- Values of __index,add, .. are called metamethods.
|
-- Values of __index,add, .. are called metamethods.
|
||||||
-- Full list. Here a is a table with the metamethod.
|
-- Full list. Here a is a table with the metamethod.
|
||||||
@@ -261,12 +251,12 @@ eatenBy = myFavs.animal -- works! thanks, metatable
|
|||||||
-- __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 Class-like tables and inheritance.
|
-- 3.2 Class-like tables and inheritance.
|
||||||
----------------------------------------------------
|
--------------------------------------------------------------------------------
|
||||||
|
|
||||||
-- Classes aren't built in; there are different ways
|
-- Classes aren't built in; there are different ways to make them using
|
||||||
-- to make them using tables and metatables.
|
-- tables and metatables.
|
||||||
|
|
||||||
-- Explanation for this example is below it.
|
-- Explanation for this example is below it.
|
||||||
|
|
||||||
@@ -286,22 +276,20 @@ mrDog = Dog:new() -- 7.
|
|||||||
mrDog:makeSound() -- 'I say woof' -- 8.
|
mrDog:makeSound() -- 'I say woof' -- 8.
|
||||||
|
|
||||||
-- 1. Dog acts like a class; it's really a table.
|
-- 1. Dog acts like a class; it's really a table.
|
||||||
-- 2. function tablename:fn(...) is the same as
|
-- 2. "function tablename:fn(...)" is the same as
|
||||||
-- function tablename.fn(self, ...)
|
-- "function tablename.fn(self, ...)", The : just adds a first arg called
|
||||||
-- The : just adds a first arg called self.
|
-- self. Read 7 & 8 below for how self gets its value.
|
||||||
-- Read 7 & 8 below for how self gets its value.
|
|
||||||
-- 3. newObj will be an instance of class Dog.
|
-- 3. newObj will be an instance of class Dog.
|
||||||
-- 4. self = the class being instantiated. Often
|
-- 4. "self" is the class being instantiated. Often self = Dog, but inheritance
|
||||||
-- self = Dog, but inheritance can change it.
|
-- can change it. newObj gets self's functions when we set both newObj's
|
||||||
-- newObj gets self's functions when we set both
|
-- metatable and self's __index to self.
|
||||||
-- newObj's metatable and self's __index to self.
|
|
||||||
-- 5. Reminder: setmetatable returns its first arg.
|
-- 5. Reminder: setmetatable returns its first arg.
|
||||||
-- 6. The : works as in 2, but this time we expect
|
-- 6. The : works as in 2, but this time we expect self to be an instance
|
||||||
-- self to be an instance instead of a class.
|
-- instead of a class.
|
||||||
-- 7. Same as Dog.new(Dog), so self = Dog in new().
|
-- 7. Same as Dog.new(Dog), so self = Dog in new().
|
||||||
-- 8. Same as mrDog.makeSound(mrDog); self = mrDog.
|
-- 8. Same as mrDog.makeSound(mrDog); self = mrDog.
|
||||||
|
|
||||||
----------------------------------------------------
|
--------------------------------------------------------------------------------
|
||||||
|
|
||||||
-- Inheritance example:
|
-- Inheritance example:
|
||||||
|
|
||||||
@@ -315,17 +303,16 @@ end
|
|||||||
seymour = LoudDog:new() -- 3.
|
seymour = LoudDog:new() -- 3.
|
||||||
seymour:makeSound() -- 'woof woof woof' -- 4.
|
seymour:makeSound() -- 'woof woof woof' -- 4.
|
||||||
|
|
||||||
|
--------------------------------------------------------------------------------
|
||||||
-- 1. LoudDog gets Dog's methods and variables.
|
-- 1. LoudDog gets Dog's methods and variables.
|
||||||
-- 2. self has a 'sound' key from new(), see 3.
|
-- 2. self has a 'sound' key from new(), see 3.
|
||||||
-- 3. Same as LoudDog.new(LoudDog), and converted to
|
-- 3. Same as "LoudDog.new(LoudDog)", and converted to "Dog.new(LoudDog)" as
|
||||||
-- Dog.new(LoudDog) as LoudDog has no 'new' key,
|
-- LoudDog has no 'new' key, but does have "__index = Dog" on its metatable.
|
||||||
-- but does have __index = Dog on its metatable.
|
-- Result: seymour's metatable is LoudDog, and "LoudDog.__index = Dog". So
|
||||||
-- Result: seymour's metatable is LoudDog, and
|
-- seymour.key will equal seymour.key, LoudDog.key, Dog.key, whichever
|
||||||
-- LoudDog.__index = Dog. So seymour.key will
|
|
||||||
-- = seymour.key, LoudDog.key, Dog.key, whichever
|
|
||||||
-- table is the first with the given key.
|
-- table is the first with the given key.
|
||||||
-- 4. The 'makeSound' key is found in LoudDog; this
|
-- 4. The 'makeSound' key is found in LoudDog; this is the same as
|
||||||
-- is the same as LoudDog.makeSound(seymour).
|
-- "LoudDog.makeSound(seymour)".
|
||||||
|
|
||||||
-- If needed, a subclass's new() is like the base's:
|
-- If needed, a subclass's new() is like the base's:
|
||||||
function LoudDog:new()
|
function LoudDog:new()
|
||||||
@@ -335,13 +322,13 @@ function LoudDog:new()
|
|||||||
return setmetatable(newObj, self)
|
return setmetatable(newObj, self)
|
||||||
end
|
end
|
||||||
|
|
||||||
----------------------------------------------------
|
--------------------------------------------------------------------------------
|
||||||
-- 4. Modules.
|
-- 4. Modules.
|
||||||
----------------------------------------------------
|
--------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
--[[ I'm commenting out this section so the rest of
|
--[[ I'm commenting out this section so the rest of this script remains
|
||||||
-- this script remains runnable.
|
-- runnable.
|
||||||
```
|
```
|
||||||
|
|
||||||
```lua
|
```lua
|
||||||
@@ -367,8 +354,8 @@ local mod = require('mod') -- Run the file mod.lua.
|
|||||||
local mod = (function ()
|
local mod = (function ()
|
||||||
<contents of mod.lua>
|
<contents of mod.lua>
|
||||||
end)()
|
end)()
|
||||||
-- It's like mod.lua is a function body, so that
|
-- It's like mod.lua is a function body, so that locals inside mod.lua are
|
||||||
-- locals inside mod.lua are invisible outside it.
|
-- invisible outside it.
|
||||||
|
|
||||||
-- This works because mod here = M in mod.lua:
|
-- This works because mod here = M in mod.lua:
|
||||||
mod.sayHello() -- Says hello to Hrunkner.
|
mod.sayHello() -- Says hello to Hrunkner.
|
||||||
@@ -376,8 +363,8 @@ mod.sayHello() -- Says hello to Hrunkner.
|
|||||||
-- This is wrong; sayMyName only exists in mod.lua:
|
-- This is wrong; sayMyName only exists in mod.lua:
|
||||||
mod.sayMyName() -- error
|
mod.sayMyName() -- error
|
||||||
|
|
||||||
-- require's return values are cached so a file is
|
-- require's return values are cached so a file is run at most once, even when
|
||||||
-- run at most once, even when require'd many times.
|
-- require'd many times.
|
||||||
|
|
||||||
-- Suppose mod2.lua contains "print('Hi!')".
|
-- Suppose mod2.lua contains "print('Hi!')".
|
||||||
local a = require('mod2') -- Prints Hi!
|
local a = require('mod2') -- Prints Hi!
|
||||||
|
Reference in New Issue
Block a user