Advertisement
ZeeDerp

asd

Jun 28th, 2016
253
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 12.14 KB | None | 0 0
  1. -- Two dashes start a one-line comment.
  2.  
  3. --[[
  4.      Adding two ['s and ]'s makes it a
  5.      multi-line comment.
  6. --]]
  7.  
  8. ----------------------------------------------------
  9. -- 1. Variables and flow control.
  10. ----------------------------------------------------
  11.  
  12. num = 42  -- All numbers are doubles.
  13. -- Don't freak out, 64-bit doubles have 52 bits for
  14. -- storing exact int values; machine precision is
  15. -- not a problem for ints that need < 52 bits.
  16.  
  17. s = 'walternate'  -- Immutable strings like Python.
  18. t = "double-quotes are also fine"
  19. u = [[ Double brackets
  20.        start and end
  21.        multi-line strings.]]
  22. t = nil  -- Undefines t; Lua has garbage collection.
  23.  
  24. -- Blocks are denoted with keywords like do/end:
  25. while num < 50 do
  26.   num = num + 1  -- No ++ or += type operators.
  27. end
  28.  
  29. -- If clauses:
  30. if num > 40 then
  31.   print('over 40')
  32. elseif s ~= 'walternate' then  -- ~= is not equals.
  33.   -- Equality check is == like Python; ok for strs.
  34.   io.write('not over 40\n')  -- Defaults to stdout.
  35. else
  36.   -- Variables are global by default.
  37.   thisIsGlobal = 5  -- Camel case is common.
  38.  
  39.   -- How to make a variable local:
  40.   local line = io.read()  -- Reads next stdin line.
  41.  
  42.   -- String concatenation uses the .. operator:
  43.   print('Winter is coming, ' .. line)
  44. end
  45.  
  46. -- Undefined variables return nil.
  47. -- This is not an error:
  48. foo = anUnknownVariable  -- Now foo = nil.
  49.  
  50. aBoolValue = false
  51.  
  52. -- Only nil and false are falsy; 0 and '' are true!
  53. if not aBoolValue then print('twas false') end
  54.  
  55. -- 'or' and 'and' are short-circuited.
  56. -- This is similar to the a?b:c operator in C/js:
  57. ans = aBoolValue and 'yes' or 'no'  --> 'no'
  58.  
  59. karlSum = 0
  60. for i = 1, 100 do  -- The range includes both ends.
  61.   karlSum = karlSum + i
  62. end
  63.  
  64. -- Use "100, 1, -1" as the range to count down:
  65. fredSum = 0
  66. for j = 100, 1, -1 do fredSum = fredSum + j end
  67.  
  68. -- In general, the range is begin, end[, step].
  69.  
  70. -- Another loop construct:
  71. repeat
  72.   print('the way of the future')
  73.   num = num - 1
  74. until num == 0
  75.  
  76.  
  77. ----------------------------------------------------
  78. -- 2. Functions.
  79. ----------------------------------------------------
  80.  
  81. function fib(n)
  82.   if n < 2 then return 1 end
  83.   return fib(n - 2) + fib(n - 1)
  84. end
  85.  
  86. -- Closures and anonymous functions are ok:
  87. function adder(x)
  88.   -- The returned function is created when adder is
  89.   -- called, and remembers the value of x:
  90.   return function (y) return x + y end
  91. end
  92. a1 = adder(9)
  93. a2 = adder(36)
  94. print(a1(16))  --> 25
  95. print(a2(64))  --> 100
  96.  
  97. -- Returns, func calls, and assignments all work
  98. -- with lists that may be mismatched in length.
  99. -- Unmatched receivers are nil;
  100. -- unmatched senders are discarded.
  101.  
  102. x, y, z = 1, 2, 3, 4
  103. -- Now x = 1, y = 2, z = 3, and 4 is thrown away.
  104.  
  105. function bar(a, b, c)
  106.   print(a, b, c)
  107.   return 4, 8, 15, 16, 23, 42
  108. end
  109.  
  110. x, y = bar('zaphod')  --> prints "zaphod  nil nil"
  111. -- Now x = 4, y = 8, values 15..42 are discarded.
  112.  
  113. -- Functions are first-class, may be local/global.
  114. -- These are the same:
  115. function f(x) return x * x end
  116. f = function (x) return x * x end
  117.  
  118. -- And so are these:
  119. local function g(x) return math.sin(x) end
  120. local g = function (x) return math.sin(x) end
  121.  
  122. -- Trig funcs work in radians, by the way.
  123.  
  124. -- Calls with one string param don't need parens:
  125. print 'hello'  -- Works fine.
  126.  
  127.  
  128. ----------------------------------------------------
  129. -- 3. Tables.
  130. ----------------------------------------------------
  131.  
  132. -- Tables = Lua's only compound data structure;
  133. --          they are associative arrays.
  134. -- Similar to php arrays or js objects, they are
  135. -- hash-lookup dicts that can also be used as lists.
  136.  
  137. -- Using tables as dictionaries / maps:
  138.  
  139. -- Dict literals have string keys by default:
  140. t = {key1 = 'value1', key2 = false}
  141.  
  142. -- String keys can use js-like dot notation:
  143. print(t.key1)  -- Prints 'value1'.
  144. t.newKey = {}  -- Adds a new key/value pair.
  145. t.key2 = nil   -- Removes key2 from the table.
  146.  
  147. -- Literal notation for any (non-nil) value as key:
  148. u = {['@!#'] = 'qbert', [{}] = 1729, [6.28] = 'tau'}
  149. print(u[6.28])  -- prints "tau"
  150.  
  151. -- Key matching is basically by value for numbers
  152. -- and strings, but by identity for tables.
  153. a = u['@!#']  -- Now a = 'qbert'.
  154. b = u[{}]     -- We might expect 1729, but it's nil:
  155. -- b = nil since the lookup fails. It fails
  156. -- because the key we used is not the same object
  157. -- as the one used to store the original value. So
  158. -- strings & numbers are more portable keys.
  159.  
  160. -- A one-table-param function call needs no parens:
  161. function h(x) print(x.key1) end
  162. h{key1 = 'Sonmi~451'}  -- Prints 'Sonmi~451'.
  163.  
  164. for key, val in pairs(u) do  -- Table iteration.
  165.   print(key, val)
  166. end
  167.  
  168. -- _G is a special table of all globals.
  169. print(_G['_G'] == _G)  -- Prints 'true'.
  170.  
  171. -- Using tables as lists / arrays:
  172.  
  173. -- List literals implicitly set up int keys:
  174. v = {'value1', 'value2', 1.21, 'gigawatts'}
  175. for i = 1, #v do  -- #v is the size of v for lists.
  176.   print(v[i])  -- Indices start at 1 !! SO CRAZY!
  177. end
  178. -- A 'list' is not a real type. v is just a table
  179. -- with consecutive integer keys, treated as a list.
  180.  
  181. ----------------------------------------------------
  182. -- 3.1 Metatables and metamethods.
  183. ----------------------------------------------------
  184.  
  185. -- A table can have a metatable that gives the table
  186. -- operator-overloadish behavior. Later we'll see
  187. -- how metatables support js-prototypey behavior.
  188.  
  189. f1 = {a = 1, b = 2}  -- Represents the fraction a/b.
  190. f2 = {a = 2, b = 3}
  191.  
  192. -- This would fail:
  193. -- s = f1 + f2
  194.  
  195. metafraction = {}
  196. function metafraction.__add(f1, f2)
  197.   sum = {}
  198.   sum.b = f1.b * f2.b
  199.   sum.a = f1.a * f2.b + f2.a * f1.b
  200.   return sum
  201. end
  202.  
  203. setmetatable(f1, metafraction)
  204. setmetatable(f2, metafraction)
  205.  
  206. s = f1 + f2  -- call __add(f1, f2) on f1's metatable
  207.  
  208. -- f1, f2 have no key for their metatable, unlike
  209. -- prototypes in js, so you must retrieve it as in
  210. -- getmetatable(f1). The metatable is a normal table
  211. -- with keys that Lua knows about, like __add.
  212.  
  213. -- But the next line fails since s has no metatable:
  214. -- t = s + s
  215. -- Class-like patterns given below would fix this.
  216.  
  217. -- An __index on a metatable overloads dot lookups:
  218. defaultFavs = {animal = 'gru', food = 'donuts'}
  219. myFavs = {food = 'pizza'}
  220. setmetatable(myFavs, {__index = defaultFavs})
  221. eatenBy = myFavs.animal  -- works! thanks, metatable
  222.  
  223. -- Direct table lookups that fail will retry using
  224. -- the metatable's __index value, and this recurses.
  225.  
  226. -- An __index value can also be a function(tbl, key)
  227. -- for more customized lookups.
  228.  
  229. -- Values of __index,add, .. are called metamethods.
  230. -- Full list. Here a is a table with the metamethod.
  231.  
  232. -- __add(a, b)                     for a + b
  233. -- __sub(a, b)                     for a - b
  234. -- __mul(a, b)                     for a * b
  235. -- __div(a, b)                     for a / b
  236. -- __mod(a, b)                     for a % b
  237. -- __pow(a, b)                     for a ^ b
  238. -- __unm(a)                        for -a
  239. -- __concat(a, b)                  for a .. b
  240. -- __len(a)                        for #a
  241. -- __eq(a, b)                      for a == b
  242. -- __lt(a, b)                      for a < b
  243. -- __le(a, b)                      for a <= b
  244. -- __index(a, b)  <fn or a table>  for a.b
  245. -- __newindex(a, b, c)             for a.b = c
  246. -- __call(a, ...)                  for a(...)
  247.  
  248. ----------------------------------------------------
  249. -- 3.2 Class-like tables and inheritance.
  250. ----------------------------------------------------
  251.  
  252. -- Classes aren't built in; there are different ways
  253. -- to make them using tables and metatables.
  254.  
  255. -- Explanation for this example is below it.
  256.  
  257. Dog = {}                                   -- 1.
  258.  
  259. function Dog:new()                         -- 2.
  260.   newObj = {sound = 'woof'}                -- 3.
  261.   self.__index = self                      -- 4.
  262.   return setmetatable(newObj, self)        -- 5.
  263. end
  264.  
  265. function Dog:makeSound()                   -- 6.
  266.   print('I say ' .. self.sound)
  267. end
  268.  
  269. mrDog = Dog:new()                          -- 7.
  270. mrDog:makeSound()  -- 'I say woof'         -- 8.
  271.  
  272. -- 1. Dog acts like a class; it's really a table.
  273. -- 2. function tablename:fn(...) is the same as
  274. --    function tablename.fn(self, ...)
  275. --    The : just adds a first arg called self.
  276. --    Read 7 & 8 below for how self gets its value.
  277. -- 3. newObj will be an instance of class Dog.
  278. -- 4. self = the class being instantiated. Often
  279. --    self = Dog, but inheritance can change it.
  280. --    newObj gets self's functions when we set both
  281. --    newObj's metatable and self's __index to self.
  282. -- 5. Reminder: setmetatable returns its first arg.
  283. -- 6. The : works as in 2, but this time we expect
  284. --    self to be an instance instead of a class.
  285. -- 7. Same as Dog.new(Dog), so self = Dog in new().
  286. -- 8. Same as mrDog.makeSound(mrDog); self = mrDog.
  287.  
  288. ----------------------------------------------------
  289.  
  290. -- Inheritance example:
  291.  
  292. LoudDog = Dog:new()                           -- 1.
  293.  
  294. function LoudDog:makeSound()
  295.   s = self.sound .. ' '                       -- 2.
  296.   print(s .. s .. s)
  297. end
  298.  
  299. seymour = LoudDog:new()                       -- 3.
  300. seymour:makeSound()  -- 'woof woof woof'      -- 4.
  301.  
  302. -- 1. LoudDog gets Dog's methods and variables.
  303. -- 2. self has a 'sound' key from new(), see 3.
  304. -- 3. Same as LoudDog.new(LoudDog), and converted to
  305. --    Dog.new(LoudDog) as LoudDog has no 'new' key,
  306. --    but does have __index = Dog on its metatable.
  307. --    Result: seymour's metatable is LoudDog, and
  308. --    LoudDog.__index = LoudDog. So seymour.key will
  309. --    = seymour.key, LoudDog.key, Dog.key, whichever
  310. --    table is the first with the given key.
  311. -- 4. The 'makeSound' key is found in LoudDog; this
  312. --    is the same as LoudDog.makeSound(seymour).
  313.  
  314. -- If needed, a subclass's new() is like the base's:
  315. function LoudDog:new()
  316.   newObj = {}
  317.   -- set up newObj
  318.   self.__index = self
  319.   return setmetatable(newObj, self)
  320. end
  321.  
  322. ----------------------------------------------------
  323. -- 4. Modules.
  324. ----------------------------------------------------
  325.  
  326.  
  327. --[[ I'm commenting out this section so the rest of
  328. --   this script remains runnable.
  329. -- Suppose the file mod.lua looks like this:
  330. local M = {}
  331.  
  332. local function sayMyName()
  333.   print('Hrunkner')
  334. end
  335.  
  336. function M.sayHello()
  337.   print('Why hello there')
  338.   sayMyName()
  339. end
  340.  
  341. return M
  342.  
  343. -- Another file can use mod.lua's functionality:
  344. local mod = require('mod')  -- Run the file mod.lua.
  345.  
  346. -- require is the standard way to include modules.
  347. -- require acts like:     (if not cached; see below)
  348. local mod = (function ()
  349.   <contents of mod.lua>
  350. end)()
  351. -- It's like mod.lua is a function body, so that
  352. -- locals inside mod.lua are invisible outside it.
  353.  
  354. -- This works because mod here = M in mod.lua:
  355. mod.sayHello()  -- Says hello to Hrunkner.
  356.  
  357. -- This is wrong; sayMyName only exists in mod.lua:
  358. mod.sayMyName()  -- error
  359.  
  360. -- require's return values are cached so a file is
  361. -- run at most once, even when require'd many times.
  362.  
  363. -- Suppose mod2.lua contains "print('Hi!')".
  364. local a = require('mod2')  -- Prints Hi!
  365. local b = require('mod2')  -- Doesn't print; a=b.
  366.  
  367. -- dofile is like require without caching:
  368. dofile('mod2')  --> Hi!
  369. dofile('mod2')  --> Hi! (runs again, unlike require)
  370.  
  371. -- loadfile loads a lua file but doesn't run it yet.
  372. f = loadfile('mod2')  -- Calling f() runs mod2.lua.
  373.  
  374. -- loadstring is loadfile for strings.
  375. g = loadstring('print(343)')  -- Returns a function.
  376. g()  -- Prints out 343; nothing printed before now.
  377.  
  378. --]]
  379.  
  380. ----------------------------------------------------
  381. -- 5. References.
  382. ----------------------------------------------------
  383.  
  384. --[[
  385.  
  386. I was excited to learn Lua so I could make games
  387. with the Löve 2D game engine. That's the why.
  388.  
  389. I started with BlackBulletIV's Lua for programmers.
  390. Next I read the official Programming in Lua book.
  391. That's the how.
  392.  
  393. It might be helpful to check out the Lua short
  394. reference on lua-users.org.
  395.  
  396. The main topics not covered are standard libraries:
  397.  * string library
  398.  * table library
  399.  * math library
  400.  * io library
  401.  * os library
  402.  
  403. By the way, this entire file is valid Lua; save it
  404. as learn.lua and run it with "lua learn.lua" !
  405.  
  406. This was first written for tylerneylon.com, and is
  407. also available as a github gist. Have fun with Lua!
  408.  
  409. --]]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement