Guest User

Untitled

a guest
Jan 22nd, 2018
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.97 KB | None | 0 0
  1. -------------------------
  2. -- tables are general container can be indexed by anything (numbers,
  3. -- tables, strings, functions...)
  4.  
  5. local function blah() end
  6. tab[blah] = blubb
  7. tab.name = blubb -- is same as
  8. tab["name"] = blubb
  9.  
  10.  
  11. -- tables are always passed as "pointers/references" never copied
  12. -- array index starts with 1 !!
  13. -- they become garbage collected when not referenced anymore
  14.  
  15. pos = {1,2,3}
  16. a = { pos = pos }
  17. pos[3] = 4
  18. pos = {1,1,1} -- overwrites local variable pos
  19. a.pos[3] -- is still 4
  20.  
  21.  
  22. -------------------------
  23. --[[ multiline
  24. comment ]]
  25.  
  26. blah = [==[ multiline string and comment
  27. can use multiple = for bracketing]==]
  28.  
  29. -------------------------
  30. --- multiple return values allow easy swapping
  31. a,b = b,a
  32.  
  33. -------------------------
  34. -- object oriented stuff
  35. -- : operate passes first arg
  36. a.func(a,blah) -- is same as
  37. a:func(blah)
  38.  
  39. -- metatables allow to index class tables
  40. myclass = {}
  41. myclassmeta = {__index = myclass}
  42. function myclass:func()
  43. self --automatic variable through : definiton for the first
  44. --arg passed to func
  45. end
  46.  
  47.  
  48. object = {}
  49. setmetatable(object,myclassmeta)
  50. object:func() -- is now same as
  51. myclass.func(object)
  52.  
  53. -------------------------
  54. --- upvalues for function specialization
  55.  
  56. function func(obj)
  57. return function()
  58. return obj * 2
  59. end
  60.  
  61. end
  62.  
  63. a = func(1)
  64. b = func(2)
  65.  
  66. a() -- returns 2
  67. b() -- returns 4
  68.  
  69. --- non passed function arguments become nil automatically
  70. function func (a,b)
  71. return a,b
  72. end
  73. a,b = func(1) -- b is "nil"
  74.  
  75. --- variable args
  76. function func(...)
  77. local a,b = ...
  78. --- a,b would be first two args
  79. --- you can also put args in a table
  80. local t = {...}
  81. end
  82.  
  83.  
  84. -------------------------
  85. --- conditional assignment chaining
  86. --- 0 is not "false", only "false" or "nil" are
  87.  
  88. a = 0
  89. b = a or 1 -- b is 0, if a was false/nil it would be 1
  90.  
  91. c = (a == 0) and b or 2 -- c is 0 (b's value)
  92.  
  93. -- the first time a value is "valid" (non-false/nil) that value is taken
  94. -- that way you can do default values
  95.  
  96. function func(a,b)
  97. a = a or 1
  98. b = b or 1
  99.  
  100. end
Add Comment
Please, Sign In to add comment