mirror of
https://github.com/adambard/learnxinyminutes-docs.git
synced 2025-05-06 06:48:32 +00:00
commit
c2571b085a
@ -45,7 +45,7 @@ end
|
|||||||
if num > 40 then
|
if num > 40 then
|
||||||
print('больше 40')
|
print('больше 40')
|
||||||
elseif s ~= 'walternate' then -- ~= обозначает "не равно".
|
elseif s ~= 'walternate' then -- ~= обозначает "не равно".
|
||||||
-- Проверка равенства это == как в Python; ok для строк.
|
-- Проверка равенства это == как в Python; работает для строк.
|
||||||
io.write('не больше 40\n') -- По умолчанию стандартный вывод.
|
io.write('не больше 40\n') -- По умолчанию стандартный вывод.
|
||||||
else
|
else
|
||||||
-- По умолчанию переменные являются глобальными.
|
-- По умолчанию переменные являются глобальными.
|
||||||
@ -54,7 +54,7 @@ else
|
|||||||
-- Как сделать локальную переменную:
|
-- Как сделать локальную переменную:
|
||||||
local line = io.read() -- Считывает введённую строку.
|
local line = io.read() -- Считывает введённую строку.
|
||||||
|
|
||||||
-- Конкатенация строк использует .. оператор:
|
-- Для конкатенации строк используется оператор .. :
|
||||||
print('Зима пришла, ' .. line)
|
print('Зима пришла, ' .. line)
|
||||||
end
|
end
|
||||||
|
|
||||||
@ -133,12 +133,12 @@ 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 = function(x) return math.sin(x) end
|
local g = function(x) return math.sin(x) end
|
||||||
-- Equivalent to local function g(x)..., except referring to g in the function
|
-- Эквивалентно для local function g(x)..., кроме ссылки на g в теле функции
|
||||||
-- 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.
|
-- 'local g' будет прототипом функции.
|
||||||
|
|
||||||
-- Trig funcs work in radians, by the way.
|
-- Так же тригонометрические функции работсют с радианами.
|
||||||
|
|
||||||
-- Вызов функции с одним текстовым параметром не требует круглых скобок:
|
-- Вызов функции с одним текстовым параметром не требует круглых скобок:
|
||||||
print 'hello' -- Работает без ошибок.
|
print 'hello' -- Работает без ошибок.
|
||||||
@ -151,32 +151,34 @@ print {} -- Тоже сработает.
|
|||||||
--------------------------------------------------------------------------------
|
--------------------------------------------------------------------------------
|
||||||
|
|
||||||
-- Таблицы = структура данных, свойственная только для Lua; это ассоциативные массивы.
|
-- Таблицы = структура данных, свойственная только для Lua; это ассоциативные массивы.
|
||||||
-- Similar to php arrays or js objects, they are hash-lookup dicts that can
|
-- Похоже на массивы в PHP или объекты в JS
|
||||||
-- also be used as lists.
|
-- Так же может использоваться как список.
|
||||||
|
|
||||||
-- Using tables as dictionaries / maps:
|
|
||||||
|
|
||||||
-- Dict literals have string keys by default:
|
-- Использование словарей:
|
||||||
|
|
||||||
|
-- Литералы имеют ключ по умолчанию:
|
||||||
t = {key1 = 'value1', key2 = false}
|
t = {key1 = 'value1', key2 = false}
|
||||||
|
|
||||||
-- String keys can use js-like dot notation:
|
-- Строковые ключи выглядят как точечная нотация в JS:
|
||||||
print(t.key1) -- Печатает 'value1'.
|
print(t.key1) -- Печатает 'value1'.
|
||||||
t.newKey = {} -- Добавляет новую пару ключ-значение.
|
t.newKey = {} -- Добавляет новую пару ключ-значение.
|
||||||
t.key2 = nil -- Удаляет key2 из таблицы.
|
t.key2 = nil -- Удаляет key2 из таблицы.
|
||||||
|
|
||||||
-- Literal notation for any (non-nil) value as key:
|
-- Литеральная нотация для любого (не пустой) значения ключа:
|
||||||
u = {['@!#'] = 'qbert', [{}] = 1729, [6.28] = 'tau'}
|
u = {['@!#'] = 'qbert', [{}] = 1729, [6.28] = 'tau'}
|
||||||
print(u[6.28]) -- пишет "tau"
|
print(u[6.28]) -- пишет "tau"
|
||||||
|
|
||||||
-- Key matching is basically by value for numbers and strings, but by identity
|
-- Ключ соответствует нужен не только для значения чисел и строк, но и для
|
||||||
-- for tables.
|
-- идентификации таблиц.
|
||||||
a = u['@!#'] -- Теперь a = 'qbert'.
|
a = u['@!#'] -- Теперь a = 'qbert'.
|
||||||
b = u[{}] -- We might expect 1729, but it's nil:
|
b = u[{}] -- Мы ожидали 1729, но получили nil:
|
||||||
-- b = nil since the lookup fails. It fails because the key we used is not the
|
-- b = nil вышла неудача. Потому что за ключ мы использовали
|
||||||
-- same object as the one used to store the original value. So strings &
|
-- не тот же объект, который использовали в оригинальном значении.
|
||||||
-- numbers are more portable keys.
|
-- Поэтому строки и числа больше подходят под ключ.
|
||||||
|
|
||||||
-- A one-table-param function call needs no parens:
|
-- Вызов фукцнии с одной таблицей в качестве аргумента
|
||||||
|
-- не нуждается в кавычках:
|
||||||
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'.
|
||||||
|
|
||||||
@ -187,24 +189,25 @@ end
|
|||||||
-- _G - это таблица со всеми глобалями.
|
-- _G - это таблица со всеми глобалями.
|
||||||
print(_G['_G'] == _G) -- Печатает 'true'.
|
print(_G['_G'] == _G) -- Печатает 'true'.
|
||||||
|
|
||||||
-- Using tables as lists / arrays:
|
-- Использование таблиц как списков / массивов:
|
||||||
|
|
||||||
-- List literals implicitly set up int keys:
|
-- Список значений с неявно заданными целочисленными ключами:
|
||||||
v = {'value1', 'value2', 1.21, 'gigawatts'}
|
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 это размер списка v.
|
||||||
print(v[i]) -- Indices start at 1 !! SO CRAZY!
|
print(v[i]) -- Начинается с ОДНОГО!
|
||||||
end
|
end
|
||||||
-- A 'list' is not a real type. v is just a table with consecutive integer
|
|
||||||
-- keys, treated as a list.
|
-- Список это таблица. v Это таблица с последовательными целочисленными
|
||||||
|
-- ключами, созданными в списке.
|
||||||
|
|
||||||
--------------------------------------------------------------------------------
|
--------------------------------------------------------------------------------
|
||||||
-- 3.1 Мета-таблицы и мета-методы.
|
-- 3.1 Мета-таблицы и мета-методы.
|
||||||
--------------------------------------------------------------------------------
|
--------------------------------------------------------------------------------
|
||||||
|
|
||||||
-- A table can have a metatable that gives the table operator-overloadish
|
-- Таблицы могут быть метатаблицами, что дает им поведение
|
||||||
-- behavior. Later we'll see how metatables support js-prototypey behavior.
|
-- перегрузки-оператора. Позже мы увидим, что метатаблицы поддерживают поведение
|
||||||
|
-- js-прототипов.
|
||||||
f1 = {a = 1, b = 2} -- Represents the fraction a/b.
|
f1 = {a = 1, b = 2} -- Представляет фракцию a/b.
|
||||||
f2 = {a = 2, b = 3}
|
f2 = {a = 2, b = 3}
|
||||||
|
|
||||||
-- Это не сработает:
|
-- Это не сработает:
|
||||||
@ -223,29 +226,29 @@ setmetatable(f2, metafraction)
|
|||||||
|
|
||||||
s = f1 + f2 -- вызывает __add(f1, f2) на мета-таблице f1
|
s = f1 + f2 -- вызывает __add(f1, f2) на мета-таблице f1
|
||||||
|
|
||||||
-- f1, f2 have no key for their metatable, unlike prototypes in js, so you must
|
-- f1, f2 не имеют ключей для своих метатаблиц в отличии от прототипов в js, поэтому
|
||||||
-- retrieve it as in getmetatable(f1). The metatable is a normal table with
|
-- ты можешь извлечь данные через getmetatable(f1). Метатаблицы это обычные таблицы с
|
||||||
-- keys that Lua knows about, like __add.
|
-- ключем, который в Lua известен как __add.
|
||||||
|
|
||||||
-- But the next line fails since s has no metatable:
|
-- Но следущая строка будет ошибочной т.к s не мета-таблица:
|
||||||
-- t = s + s
|
-- t = s + s
|
||||||
-- Class-like patterns given below would fix this.
|
-- Шаблоны классов приведенные ниже смогут это исправить.
|
||||||
|
|
||||||
-- An __index on a metatable overloads dot lookups:
|
-- __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 -- работает! спасибо, мета-таблица.
|
||||||
|
|
||||||
--------------------------------------------------------------------------------
|
--------------------------------------------------------------------------------
|
||||||
-- Direct table lookups that fail will retry using the metatable's __index
|
-- Прямой табличный поиск не будет пытаться передавать с помощью __index
|
||||||
-- value, and this recurses.
|
-- значения, и её рекурсии.
|
||||||
|
|
||||||
-- An __index value can also be a function(tbl, key) for more customized
|
-- __index значения так же могут быть function(tbl, key) для настроенного
|
||||||
-- lookups.
|
-- просмотра.
|
||||||
|
|
||||||
-- Values of __index,add, .. are called metamethods.
|
-- Значения типа __index,add, ... называются метаметодами.
|
||||||
-- Full list. Here a is a table with the metamethod.
|
-- Полный список. Здесь таблицы с метаметодами.
|
||||||
|
|
||||||
-- __add(a, b) для a + b
|
-- __add(a, b) для a + b
|
||||||
-- __sub(a, b) для a - b
|
-- __sub(a, b) для a - b
|
||||||
@ -264,13 +267,14 @@ eatenBy = myFavs.animal -- работает! спасибо, мета-табл
|
|||||||
-- __call(a, ...) для a(...)
|
-- __call(a, ...) для a(...)
|
||||||
|
|
||||||
--------------------------------------------------------------------------------
|
--------------------------------------------------------------------------------
|
||||||
-- 3.2 Class-like tables and inheritance.
|
-- 3.2 Классы и наследования.
|
||||||
--------------------------------------------------------------------------------
|
--------------------------------------------------------------------------------
|
||||||
|
|
||||||
-- Classes aren't built in; there are different ways to make them using
|
-- В Lua нет поддержки классов на уровне языка;
|
||||||
-- tables and metatables.
|
-- Однако существуют разные способы их создания с помощью
|
||||||
|
-- таблиц и метатаблиц.
|
||||||
|
|
||||||
-- Explanation for this example is below it.
|
-- Пример классам находится ниже.
|
||||||
|
|
||||||
Dog = {} -- 1.
|
Dog = {} -- 1.
|
||||||
|
|
||||||
@ -287,23 +291,22 @@ end
|
|||||||
mrDog = Dog:new() -- 7.
|
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 похоже на класс; но это таблица.
|
||||||
-- 2. "function tablename:fn(...)" is the same as
|
-- 2. "function tablename:fn(...)" как и
|
||||||
-- "function tablename.fn(self, ...)", The : just adds a first arg called
|
-- "function tablename.fn(self, ...)", Просто : добавляет первый аргумент
|
||||||
-- self. Read 7 & 8 below for how self gets its value.
|
-- перед собой. Читай 7 и 8 чтоб понять как self получает значение.
|
||||||
-- 3. newObj will be an instance of class Dog.
|
-- 3. newObj это экземпляр класса Dog.
|
||||||
-- 4. "self" is the class being instantiated. Often self = Dog, but inheritance
|
-- 4. "self" есть класс являющийся экземпляром. Зачастую self = Dog, но экземляр
|
||||||
-- can change it. newObj gets self's functions when we set both newObj's
|
-- может поменять это. newObj получит свои функции, когда мы установим newObj как
|
||||||
-- metatable and self's __index to self.
|
-- метатаблицу и __index на себя.
|
||||||
-- 5. Reminder: setmetatable returns its first arg.
|
-- 5. Помни: setmetatable возвращает первый аргумент.
|
||||||
-- 6. The : works as in 2, but this time we expect self to be an instance
|
-- 6. ":" Работает в 2 стороны, но в этот раз мы ожидмаем, что self будет экземпляром
|
||||||
-- instead of a class.
|
-- а не классом.
|
||||||
-- 7. Same as Dog.new(Dog), so self = Dog in new().
|
-- 7. Dog.new(Dog), тоже самое что self = Dog in new().
|
||||||
-- 8. Same as mrDog.makeSound(mrDog); self = mrDog.
|
-- 8. mrDog.makeSound(mrDog) будет self = mrDog.
|
||||||
|
|
||||||
--------------------------------------------------------------------------------
|
--------------------------------------------------------------------------------
|
||||||
|
|
||||||
-- Inheritance example:
|
-- Пример наследования:
|
||||||
|
|
||||||
LoudDog = Dog:new() -- 1.
|
LoudDog = Dog:new() -- 1.
|
||||||
|
|
||||||
@ -316,17 +319,16 @@ 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 получит методы и переменные класса Dog.
|
||||||
-- 2. self has a 'sound' key from new(), see 3.
|
-- 2. self будет 'sound' ключ для new(), смотри 3й пункт.
|
||||||
-- 3. Same as "LoudDog.new(LoudDog)", and converted to "Dog.new(LoudDog)" as
|
-- 3. Так же как "LoudDog.new(LoudDog)" и переделанный в "Dog.new(LoudDog)"
|
||||||
-- LoudDog has no 'new' key, but does have "__index = Dog" on its metatable.
|
-- LoudDog не имеет ключ 'new', но может выполнить "__index = Dog" в этой метатаблице
|
||||||
-- Result: seymour's metatable is LoudDog, and "LoudDog.__index = Dog". So
|
-- Результат: Метатаблица seymour стала LoudDog и "LoudDog.__index = Dog"
|
||||||
-- seymour.key will equal seymour.key, LoudDog.key, Dog.key, whichever
|
-- Так же seymour.key будет равна seymour.key, LoudDog.key, Dog.key,
|
||||||
-- table is the first with the given key.
|
-- в зависимости от того какая таблица будет с первым ключем.
|
||||||
-- 4. The 'makeSound' key is found in LoudDog; this is the same as
|
-- 4. 'makeSound' ключ найден в LoudDog; и выглдяит как "LoudDog.makeSound(seymour)".
|
||||||
-- "LoudDog.makeSound(seymour)".
|
|
||||||
|
|
||||||
-- If needed, a subclass's new() is like the base's:
|
-- При необходимости, подкласс new() будет базовым.
|
||||||
function LoudDog:new()
|
function LoudDog:new()
|
||||||
local newObj = {}
|
local newObj = {}
|
||||||
-- set up newObj
|
-- set up newObj
|
||||||
@ -339,12 +341,12 @@ end
|
|||||||
--------------------------------------------------------------------------------
|
--------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
--[[ I'm commenting out this section so the rest of this script remains
|
--[[ Я закомментировал этот раздел так как часть скрипта остается
|
||||||
-- runnable.
|
-- работоспособной.
|
||||||
```
|
```
|
||||||
|
|
||||||
```lua
|
```lua
|
||||||
-- Suppose the file mod.lua looks like this:
|
-- Предположим файл mod.lua будет выглядеть так:
|
||||||
local M = {}
|
local M = {}
|
||||||
|
|
||||||
local function sayMyName()
|
local function sayMyName()
|
||||||
@ -358,57 +360,55 @@ end
|
|||||||
|
|
||||||
return M
|
return M
|
||||||
|
|
||||||
-- Another file can use mod.lua's functionality:
|
-- Иные файлы могут использовать функционал mod.lua:
|
||||||
local mod = require('mod') -- Run the file mod.lua.
|
local mod = require('mod') -- Запустим файл mod.lua.
|
||||||
|
|
||||||
-- require is the standard way to include modules.
|
-- require - подключает модули.
|
||||||
-- require acts like: (if not cached; see below)
|
-- require выглядит так: (если не кешируется; смотри ниже)
|
||||||
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 locals inside mod.lua are
|
-- Тело функции mod.lua является локальным, поэтому
|
||||||
-- invisible outside it.
|
-- содержимое не видимо за телом функции.
|
||||||
|
|
||||||
-- This works because mod here = M in mod.lua:
|
-- Это работает так как mod здесь = M в mod.lua:
|
||||||
mod.sayHello() -- Says hello to Hrunkner.
|
mod.sayHello() -- Скажет слово Hrunkner.
|
||||||
|
|
||||||
-- This is wrong; sayMyName only exists in mod.lua:
|
-- Это будет ошибочным; sayMyName доступен только в mod.lua:
|
||||||
mod.sayMyName() -- error
|
mod.sayMyName() -- ошибка
|
||||||
|
|
||||||
-- require's return values are cached so a file is run at most once, even when
|
-- require возвращает значения кеша файла вызванного не более одного раза, даже когда
|
||||||
-- require'd many times.
|
-- требуется много раз.
|
||||||
|
|
||||||
-- Suppose mod2.lua contains "print('Hi!')".
|
-- Предположим mod2.lua содержит "print('Hi!')".
|
||||||
local a = require('mod2') -- Prints Hi!
|
local a = require('mod2') -- Напишет Hi!
|
||||||
local b = require('mod2') -- Doesn't print; a=b.
|
local b = require('mod2') -- Не напишет; a=b.
|
||||||
|
|
||||||
-- dofile is like require without caching:
|
-- dofile работает без кэша:
|
||||||
dofile('mod2') --> Hi!
|
dofile('mod2') --> Hi!
|
||||||
dofile('mod2') --> Hi! (runs again, unlike require)
|
dofile('mod2') --> Hi! (напишет снова)
|
||||||
|
|
||||||
-- loadfile loads a lua file but doesn't run it yet.
|
-- loadfile загружает lua файл, но не запускает его.
|
||||||
f = loadfile('mod2') -- Calling f() runs mod2.lua.
|
f = loadfile('mod2') -- Вызовет f() запустит mod2.lua.
|
||||||
|
|
||||||
-- loadstring is loadfile for strings.
|
-- loadstring это loadfile для строк.
|
||||||
g = loadstring('print(343)') -- Returns a function.
|
g = loadstring('print(343)') -- Вернет функцию.
|
||||||
g() -- Prints out 343; nothing printed before now.
|
g() -- Напишет 343.
|
||||||
|
|
||||||
--]]
|
--]]
|
||||||
|
|
||||||
```
|
```
|
||||||
## References
|
## Примечание (от автора)
|
||||||
|
|
||||||
I was excited to learn Lua so I could make games
|
Я был взволнован, когда узнал что с Lua я могу делать игры при помощи <a href="http://love2d.org/">Love 2D game engine</a>. Вот почему.
|
||||||
with the <a href="http://love2d.org/">Love 2D game engine</a>. That's the why.
|
|
||||||
|
|
||||||
I started with <a href="http://nova-fusion.com/2012/08/27/lua-for-programmers-part-1/">BlackBulletIV's Lua for programmers</a>.
|
Я начинал с <a href="http://nova-fusion.com/2012/08/27/lua-for-programmers-part-1/">BlackBulletIV's Lua for programmers</a>.
|
||||||
Next I read the official <a href="http://www.lua.org/pil/contents.html">Programming in Lua</a> book.
|
Затем я прочитал официальную <a href="http://www.lua.org/pil/contents.html">Документацию по Lua</a>.
|
||||||
That's the how.
|
|
||||||
|
|
||||||
It might be helpful to check out the <a href="http://lua-users.org/files/wiki_insecure/users/thomasl/luarefv51.pdf">Lua short
|
Так же может быть полезным <a href="http://lua-users.org/files/wiki_insecure/users/thomasl/luarefv51.pdf">Lua short
|
||||||
reference</a> on lua-users.org.
|
reference</a> на lua-users.org.
|
||||||
|
|
||||||
The main topics not covered are standard libraries:
|
Основные темы не охваченные стандартной библиотекой:
|
||||||
|
|
||||||
* <a href="http://lua-users.org/wiki/StringLibraryTutorial">string library</a>
|
* <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/TableLibraryTutorial">table library</a>
|
||||||
@ -416,8 +416,9 @@ The main topics not covered are standard libraries:
|
|||||||
* <a href="http://lua-users.org/wiki/IoLibraryTutorial">io library</a>
|
* <a href="http://lua-users.org/wiki/IoLibraryTutorial">io library</a>
|
||||||
* <a href="http://lua-users.org/wiki/OsLibraryTutorial">os library</a>
|
* <a href="http://lua-users.org/wiki/OsLibraryTutorial">os library</a>
|
||||||
|
|
||||||
By the way, the entire file is valid Lua; save it
|
Весь файл написан на Lua; сохрани его как learn.lua и запусти при помощи "lua learn.lua" !
|
||||||
as learn.lua and run it with "lua learn.lua" !
|
|
||||||
|
Это была моя первая статья для tylerneylon.com, которая так же доступна тут <a href="https://gist.github.com/tylerneylon/5853042">github gist</a>.
|
||||||
|
|
||||||
|
Удачи с Lua!
|
||||||
|
|
||||||
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!
|
|
||||||
|
Loading…
Reference in New Issue
Block a user