×

Langue

Fermer
Atelier 801
  • Forums
  • Dev Tracker
  • Connexion
    • English Français
      Português do Brasil Español
      Türkçe Polski
      Magyar Română
      العربية Skandinavisk
      Nederlands Deutsch
      Bahasa Indonesia Русский
      中文 Filipino
      Lietuvių kalba 日本語
      Suomi עברית
      Italiano Česky
      Hrvatski Slovensky
      Български Latviešu
      Estonian
  • Langue
  • Forums
  • /
  • Transformice
  • /
  • Modules
  • /
  • [Tutorial] Learn Lua in 15 minutes (Not for kidos!)
1 / 2 › »
[Tutorial] Learn Lua in 15 minutes (Not for kidos!)
Bolodefchoco
« Sénateur »
1517521260000
    • Bolodefchoco#0095
    • Profil
    • Derniers messages
    • Tribu
#1
  9
Code Lua

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
-- Two dashes start a one-line comment.

--[[
Adding two ['s and ]'s makes it a
multi-line comment.
--]]

----------------------------------------------------
-- 1. Variables and flow control.
----------------------------------------------------

num = 42 -- All numbers are doubles.
-- Don't freak out, 64-bit doubles have 52 bits for
-- storing exact int values; machine precision is
-- not a problem for ints that need < 52 bits.

s = 'walternate' -- Immutable strings like Python.
t = "double-quotes are also fine"
u = [[ Double brackets
start and end
multi-line strings.]]
t = nil -- Undefines t; Lua has garbage collection.

-- Blocks are denoted with keywords like do/end:
while num < 50 do
num = num + 1 -- No ++ or += type operators.
end

-- If clauses:
if num > 40 then
print('over 40')
elseif s ~= 'walternate' then -- ~= is not equals.
-- Equality check is == like Python; ok for strs.
io.write('not over 40\n') -- Defaults to stdout.
else
-- Variables are global by default.
thisIsGlobal = 5 -- Camel case is common.

-- How to make a variable local:
local line = io.read() -- Reads next stdin line.

-- String concatenation uses the .. operator:
print('Winter is coming, ' .. line)
end

-- Undefined variables return nil.
-- This is not an error:
foo = anUnknownVariable -- Now foo = nil.

aBoolValue = false

-- Only nil and false are falsy; 0 and '' are true!
if not aBoolValue then print('twas false') end

-- 'or' and 'and' are short-circuited.
-- This is similar to the a?b:c operator in C/js:
ans = aBoolValue and 'yes' or 'no' --> 'no'

karlSum = 0
for i = 1, 100 do -- The range includes both ends.
karlSum = karlSum + i
end

-- Use "100, 1, -1" as the range to count down:
fredSum = 0
for j = 100, 1, -1 do fredSum = fredSum + j end

-- In general, the range is begin, end[, step].

-- Another loop construct:
repeat
print('the way of the future')
num = num - 1
until num == 0


----------------------------------------------------
-- 2. Functions.
----------------------------------------------------

function fib(n)
if n < 2 then return 1 end
return fib(n - 2) + fib(n - 1)
end

-- Closures and anonymous functions are ok:
function adder(x)
-- The returned function is created when adder is
-- called, and remembers the value of x:
return function (y) return x + y end
end
a1 = adder(9)
a2 = adder(36)
print(a1(16)) --> 25
print(a2(64)) --> 100

-- Returns, func calls, and assignments all work
-- with lists that may be mismatched in length.
-- Unmatched receivers are nil;
-- unmatched senders are discarded.

x, y, z = 1, 2, 3, 4
-- Now x = 1, y = 2, z = 3, and 4 is thrown away.

function bar(a, b, c)
print(a, b, c)
return 4, 8, 15, 16, 23, 42
end

x, y = bar('zaphod') --> prints "zaphod nil nil"
-- Now x = 4, y = 8, values 15..42 are discarded.

-- Functions are first-class, may be local/global.
-- These are the same:
function f(x) return x * x end
f = function (x) return x * x end

-- And so are these:
local function g(x) return math.sin(x) end
local g; g = function (x) return math.sin(x) end
-- the 'local g' decl makes g-self-references ok.

-- Trig funcs work in radians, by the way.

-- Calls with one string param don't need parens:
print 'hello' -- Works fine.


----------------------------------------------------
-- 3. Tables.
----------------------------------------------------

-- Tables = Lua's only compound data structure;
-- they are associative arrays.
-- Similar to php arrays or js objects, they are
-- hash-lookup dicts that can also be used as lists.

-- Using tables as dictionaries / maps:

-- Dict literals have string keys by default:
t = {key1 = 'value1', key2 = false}

-- String keys can use js-like dot notation:
print(t.key1) -- Prints 'value1'.
t.newKey = {} -- Adds a new key/value pair.
t.key2 = nil -- Removes key2 from the table.

-- Literal notation for any (non-nil) value as key:
u = {['@!#'] = 'qbert', [{}] = 1729, [6.28] = 'tau'}
print(u[6.28]) -- prints "tau"

-- Key matching is basically by value for numbers
-- and strings, but by identity for tables.
a = u['@!#'] -- Now a = 'qbert'.
b = u[{}] -- We might expect 1729, but it's nil:
-- b = nil since the lookup fails. It fails
-- because the key we used is not the 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
h{key1 = 'Sonmi~451'} -- Prints 'Sonmi~451'.

for key, val in pairs(u) do -- Table iteration.
print(key, val)
end

-- _G is a special table of all globals.
print(_G['_G'] == _G) -- Prints 'true'.

-- Using tables as lists / arrays:

-- List literals implicitly set up int keys:
v = {'value1', 'value2', 1.21, 'gigawatts'}
for i = 1, #v do -- #v is the size of v for lists.
print(v[i]) -- Indices start at 1 !! SO CRAZY!
end
-- A 'list' is not a real type. v is just a table
-- with consecutive integer keys, treated as a list.

----------------------------------------------------
-- 3.1 Metatables and metamethods.
----------------------------------------------------

-- A table can have a metatable that gives the table
-- operator-overloadish behavior. Later we'll see
-- how metatables support js-prototypey behavior.

f1 = {a = 1, b = 2} -- Represents the fraction a/b.
f2 = {a = 2, b = 3}

-- This would fail:
-- s = f1 + f2

metafraction = {}
function metafraction.__add(f1, f2)
sum = {}
sum.b = f1.b * f2.b
sum.a = f1.a * f2.b + f2.a * f1.b
return sum
end

setmetatable(f1, metafraction)
setmetatable(f2, metafraction)

s = f1 + f2 -- call __add(f1, f2) on f1's metatable

-- f1, f2 have no key for their metatable, unlike
-- prototypes in js, so you must retrieve it as in
-- getmetatable(f1). The metatable is a normal table
-- with keys that Lua knows about, like __add.

-- But the next line fails since s has no metatable:
-- t = s + s
-- Class-like patterns given below would fix this.

-- An __index on a metatable overloads dot lookups:
defaultFavs = {animal = 'gru', food = 'donuts'}
myFavs = {food = 'pizza'}
setmetatable(myFavs, {__index = defaultFavs})
eatenBy = myFavs.animal -- works! thanks, metatable

-- 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)
-- for more customized lookups.

-- Values of __index,add, .. are called metamethods.
-- Full list. Here a is a table with the metamethod.

-- __add(a, b) for a + b
-- __sub(a, b) for a - b
-- __mul(a, b) for a * b
-- __div(a, b) for a / b
-- __mod(a, b) for a % b
-- __pow(a, b) for a ^ b
-- __unm(a) for -a
-- __concat(a, b) for a .. b
-- __len(a) for #a
-- __eq(a, b) for a == b
-- __lt(a, b) for a < b
-- __le(a, b) for a <= b
-- __index(a, b) <fn or a table> for a.b
-- __newindex(a, b, c) for a.b = c
-- __call(a, ...) for a(...)

----------------------------------------------------
-- 3.2 Class-like tables and inheritance.
----------------------------------------------------

-- Classes aren't built in; there are different ways
-- to make them using tables and metatables.

-- Explanation for this example is below it.

Dog = {} -- 1.

function Dog:new() -- 2.
local newObj = {sound = 'woof'} -- 3.
self.__index = self -- 4.
return setmetatable(newObj, self) -- 5.
end

function Dog:makeSound() -- 6.
print('I say ' .. self.sound)
end

mrDog = Dog:new() -- 7.
mrDog:makeSound() -- 'I say woof' -- 8.

-- 1. Dog acts like a class; it's really a table.
-- 2. function tablename:fn(...) is the same as
-- function tablename.fn(self, ...)
-- The : just adds a first arg called self.
-- Read 7 & 8 below for how self gets its value.
-- 3. newObj will be an instance of class Dog.
-- 4. self = the class being instantiated. Often
-- self = Dog, but inheritance can change it.
-- newObj gets self's functions when we set both
-- newObj's metatable and self's __index to self.
-- 5. Reminder: setmetatable returns its first arg.
-- 6. The : works as in 2, but this time we expect
-- self to be an instance instead of a class.
-- 7. Same as Dog.new(Dog), so self = Dog in new().
-- 8. Same as mrDog.makeSound(mrDog); self = mrDog.

----------------------------------------------------

-- Inheritance example:

LoudDog = Dog:new() -- 1.

function LoudDog:makeSound()
local s = self.sound .. ' ' -- 2.
print(s .. s .. s)
end

seymour = LoudDog:new() -- 3.
seymour:makeSound() -- 'woof woof woof' -- 4.

-- 1. LoudDog gets Dog's methods and variables.
-- 2. self has a 'sound' key from new(), see 3.
-- 3. Same as LoudDog.new(LoudDog), and converted to
-- Dog.new(LoudDog) as LoudDog has no 'new' key,
-- but does have __index = Dog on its metatable.
-- Result: seymour's metatable is LoudDog, and
-- LoudDog.__index = LoudDog. So seymour.key will
-- = seymour.key, LoudDog.key, Dog.key, whichever
-- table is the first with the given key.
-- 4. The 'makeSound' key is found in LoudDog; this
-- is the same as LoudDog.makeSound(seymour).

-- If needed, a subclass's new() is like the base's:
function LoudDog:new()
local newObj = {}
-- set up newObj
self.__index = self
return setmetatable(newObj, self)
end

--[[
Created by the Github's user Tylerneylon (see official https://gist.github.com/tylerneylon/5853042)

Comment any doubts in this thread
Run the script, it runs!

Have fun with Lua (:.
]]

Dernière modification le 1518880800000
Censere
« Consul »
1517525460000
    • Censere#0095
    • Profil
    • Derniers messages
    • Tribu
#2
  1
Very nice, I understood most of this.
Bolodefchoco
« Sénateur »
1517525700000
    • Bolodefchoco#0095
    • Profil
    • Derniers messages
    • Tribu
#3
  1
Drescen a dit :
Very nice, I understood most of this.

Yay :3 Thanks
Koruto
« Citoyen »
1517537700000
    • Koruto#2851
    • Profil
    • Derniers messages
    • Tribu
#4
  1
Thanx a lot and though i have already read it.

Dernière modification le 1517578920000
King_seniru
« Censeur »
1517538840000
    • King_seniru#5890
    • Profil
    • Derniers messages
    • Tribu
#5
  2
I have seen this in a web site. I think it is this

Dernière modification le 1517538900000
Bolodefchoco
« Sénateur »
1517540100000
    • Bolodefchoco#0095
    • Profil
    • Derniers messages
    • Tribu
#6
  2
Indika123 a dit :
I have seen this in a web site. I think it is this

https://image.prntscr.com/image/39By7EW0QAOjwrw7R05VqQ.png

:D
Kimsterjay
« Consul »
1517556360000
    • Kimsterjay#0000
    • Profil
    • Derniers messages
    • Tribu
#7
  2
Niceeee
Smutny_nalesnik
« Consul »
1517705220000
    • Smutny_nalesnik#0000
    • Profil
    • Derniers messages
    • Tribu
#8
  2
So useful uwu
Good work o/
Bolodefchoco
« Sénateur »
1517762280000
    • Bolodefchoco#0095
    • Profil
    • Derniers messages
    • Tribu
#9
  1
Thanks ;)
Bemmh
« Consul »
1517768460000
    • Bemmh#0095
    • Profil
    • Derniers messages
    • Tribu
#10
  1
If only my brain would understand this ; _ ;

Good job, though!
Bolodefchoco
« Sénateur »
1517773680000
    • Bolodefchoco#0095
    • Profil
    • Derniers messages
    • Tribu
#11
  1
Bemmh a dit :
If only my brain would understand this ; _ ;

Good job, though!

Well, this is not a tutorial for beginners, but for those who already programs but not in Lua.
It's like a big comparsion between other languages.

Introducing someone to Lua is not that easy when they don't know how to program in Python, C, or something like that xD
Bemmh
« Consul »
1517805060000
    • Bemmh#0095
    • Profil
    • Derniers messages
    • Tribu
#12
  1
Bolodefchoco a dit :
Bemmh a dit :
If only my brain would understand this ; _ ;

Good job, though!

Well, this is not a tutorial for beginners, but for those who already programs but not in Lua.
It's like a big comparsion between other languages.

Introducing someone to Lua is not that easy when they don't know how to program in Python, C, or something like that xD

Of course! I still just wish I’d understand!
Sunflowers
« Censeur »
1517829960000
    • Sunflowers#3568
    • Profil
    • Derniers messages
#13
  2
A useful guide for new players who are interested in LUA, nice job.
Jordy
« Consul »
1517843820000
    • Jordy#0015
    • Profil
    • Derniers messages
    • Tribu
#14
  2
Nice guide, Lua is fun!
Bolodefchoco
« Sénateur »
1517844840000
    • Bolodefchoco#0095
    • Profil
    • Derniers messages
    • Tribu
#15
  1
Jordynl a dit :
Nice guide, Lua is fun!

oh no a mod commented in my thread he is gonna lock it

Skittlesuni a dit :
A useful guide for new players who are interested in LUA, nice job.

Yes, but this tutorial was written for programmers, not for beginners. (You can still learn, but may be a bit harder here)


Bemmh a dit :
Bolodefchoco a dit :
Bemmh a dit :
If only my brain would understand this ; _ ;

Good job, though!

Well, this is not a tutorial for beginners, but for those who already programs but not in Lua.
It's like a big comparsion between other languages.

Introducing someone to Lua is not that easy when they don't know how to program in Python, C, or something like that xD

Of course! I still just wish I’d understand!

You'll! Trust yourself and read all those manuals hehe
Honorabilis
« Consul »
1517854080000
    • Honorabilis#0000
    • Profil
    • Derniers messages
    • Tribu
#16
  2
Yes, I understood that too.
Iha_ya
1518803340000
    • Iha_ya#6361
    • Profil
    • Derniers messages
    • Tribu
#17
[Modéré par Batt_mellamy, raison : Пожалуйста, не говорите по-русски на Английском форуме. Чтобы перейти на русский форум, зайдите на главную страницу и выберите российский флаг.]
Iha_ya
1518803460000
    • Iha_ya#6361
    • Profil
    • Derniers messages
    • Tribu
#18
[Modéré par Batt_mellamy, raison : Multi-post]
Iha_ya
1518803460000
    • Iha_ya#6361
    • Profil
    • Derniers messages
    • Tribu
#19
[Modéré par Batt_mellamy, raison : Multi-post]
Iha_ya
1518803520000
    • Iha_ya#6361
    • Profil
    • Derniers messages
    • Tribu
#20
[Modéré par Batt_mellamy, raison : Multi-post]
  • Forums
  • /
  • Transformice
  • /
  • Modules
  • /
  • [Tutorial] Learn Lua in 15 minutes (Not for kidos!)
1 / 2 › »
© Atelier801 2018

Equipe Conditions Générales d'Utilisation Politique de Confidentialité Contact

Version 1.27