Advertisement
theTANCO

LuaMetatables.txt

Feb 24th, 2023 (edited)
244
1
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 17.49 KB | Help | 1 0
  1. This is a guide for metatables, metamethods, and what they do in Lua.
  2. Metatables allow you to change the behavior of tables.
  3. Metamethods are the functions that control the behaviors.
  4.  
  5. You need 2 tables to create a metatable.
  6. The main table is the parent that is publicly exposed to the user.
  7. The second table is the metatable that will contain your metamethods.
  8.  
  9. You set a metatable by calling the setmetatable function.
  10.  
  11. Usage: tab = setmetatable(parent, metatable)
  12.  
  13. To get the contents of a metatable you call getmetatable().
  14.  
  15. Usage: getmetatable(table)
  16.  
  17. Most metamethods are functions, and the first argument to the functions is
  18. always the parent table.
  19. Not all metamethods are available in every version of Lua. The ones I know of
  20. will be noted in the "Known Lua Versions" sections below each metamethod.
  21. I don't fully understand how to use every metamethod. The ones I don't
  22. understand will be noted below each metamethod.
  23. I did my best to explain and demonstrate how everything works. Let me know if I
  24. need to clarify anything.
  25.  
  26.  
  27.  
  28. +--------------------------------------+
  29. | Table of Contents |
  30. +-----+--------------------------------+
  31. | 46 | Known Lua Versions |
  32. +-----+-----------+--------------------+
  33. | 55 | Operators | Calculation |
  34. | 153 | Operators | Bitwise |
  35. | 249 | Operators | Comparison |
  36. | 321 | Operators | Misc. |
  37. | 359 | Behavior | Indexing |
  38. | 428 | Behavior | Calling |
  39. | 458 | Behavior | Iteration |
  40. | 532 | Behavior | Garbage Collection |
  41. +-----+-----------+--------------------+
  42.  
  43.  
  44.  
  45. +--------------------+
  46. | Known Lua Versions |
  47. +--------------------+
  48. Lua 5.4
  49. ComputerCraft - Lua 5.0, 5.2, 5.3
  50. ChilloutVR - Lua 5.2
  51.  
  52.  
  53.  
  54. +-----------+-------------+
  55. | Operators | Calculation |
  56. +-----------+-------------+
  57.  
  58.  
  59.  
  60. __unm = <function>
  61. --------------------------------------------------------------------------------
  62. http://www.lua.org/manual/5.4/manual.html#2.4
  63. This method runs when negation is performed on the parent table.
  64.  
  65. Usage: -tab
  66. Function: __unm(self)
  67. Return: <any value>
  68.  
  69.  
  70.  
  71. __add = <function>
  72. --------------------------------------------------------------------------------
  73. http://www.lua.org/manual/5.4/manual.html#2.4
  74. This method runs when addition is performed on the parent table.
  75.  
  76. Usage: tab + n
  77. Function: __add(self, n)
  78. Return: <any value>
  79.  
  80.  
  81.  
  82. __sub = <function>
  83. --------------------------------------------------------------------------------
  84. http://www.lua.org/manual/5.4/manual.html#2.4
  85. This method runs when subtraction is performed on the parent table.
  86.  
  87. Usage: tab - n
  88. Function: __sub(self, n)
  89. Return: <any value>
  90.  
  91.  
  92.  
  93. __mul = <function>
  94. --------------------------------------------------------------------------------
  95. http://www.lua.org/manual/5.4/manual.html#2.4
  96. This method runs when multiplication is performed on the parent.
  97.  
  98. Usage: tab * n
  99. Function: __mul(self, n)
  100. Return: <any value>
  101.  
  102.  
  103.  
  104. __div = <function>
  105. --------------------------------------------------------------------------------
  106. http://www.lua.org/manual/5.4/manual.html#2.4
  107. This method runs when division is performed on the parent.
  108.  
  109. Usage: tab / n
  110. Function: __div(self, n)
  111. Return: <any value>
  112.  
  113.  
  114.  
  115. __mod = <function>
  116. --------------------------------------------------------------------------------
  117. http://www.lua.org/manual/5.4/manual.html#2.4
  118. This method runs when modulus is performed on the parent.
  119.  
  120. Usage: tab % n
  121. Function: __mod(self, n)
  122. Return: <any value>
  123.  
  124.  
  125.  
  126. __idiv = <function>
  127. --------------------------------------------------------------------------------
  128. http://www.lua.org/manual/5.4/manual.html#2.4
  129. This method runs when floor division is performed on the parent.
  130.  
  131. Usage: tab // n
  132. Function: __idiv(self, n)
  133. Return: <any value>
  134.  
  135. Floor division is equal to math.floor(num1 / num2).
  136. (Currently not present in ComputerCraft.)
  137. (Currently not present in ChilloutVR.)
  138.  
  139.  
  140.  
  141. __pow = <function>
  142. --------------------------------------------------------------------------------
  143. http://www.lua.org/manual/5.4/manual.html#2.4
  144. This method runs when power is performed on the parent.
  145.  
  146. Usage: tab ^ n
  147. Function: __pow(self, n)
  148. Return: <any value>
  149.  
  150.  
  151.  
  152. +-----------+---------+
  153. | Operators | Bitwise |
  154. +-----------+---------+
  155.  
  156.  
  157.  
  158. __band = <function>
  159. --------------------------------------------------------------------------------
  160. http://www.lua.org/manual/5.4/manual.html#2.4
  161. This method runs when bitwise AND is performed on the parent.
  162.  
  163. Usage: tab & n
  164. Function: __band(self, n)
  165. Return: <any value>
  166.  
  167. (Not present in Lua 5.2 or lower.)
  168. (Currently not present in ComputerCraft.)
  169. (Currently not present in ChilloutVR.)
  170.  
  171.  
  172.  
  173. __bor = <function>
  174. --------------------------------------------------------------------------------
  175. http://www.lua.org/manual/5.4/manual.html#2.4
  176. This method runs when bitwise OR is performed on the parent.
  177.  
  178. Usage: tab | n
  179. Function: __bor(self, n)
  180. Return: <any value>
  181.  
  182. (Not present in Lua 5.2 or lower.)
  183. (Currently not present in ComputerCraft.)
  184. (Currently not present in ChilloutVR.)
  185.  
  186.  
  187.  
  188. __bxor = <function>
  189. --------------------------------------------------------------------------------
  190. http://www.lua.org/manual/5.4/manual.html#2.4
  191. This method runs when bitwise XOR is performed on the parent.
  192.  
  193. Usage: tab ~ n
  194. Function: __bxor(self, n)
  195. Return: <any value>
  196.  
  197. (Not present in Lua 5.2 or lower.)
  198. (Currently not present in ComputerCraft.)
  199. (Currently not present in ChilloutVR.)
  200.  
  201.  
  202.  
  203. __bnot = <function>
  204. --------------------------------------------------------------------------------
  205. http://www.lua.org/manual/5.4/manual.html#2.4
  206. This method runs when bitwise NOT is performed on the parent.
  207.  
  208. Usage: ~tab
  209. Function: __bnot(self)
  210. Return: <any value>
  211.  
  212. (Not present in Lua 5.2 or lower.)
  213. (Currently not present in ComputerCraft.)
  214. (Currently not present in ChilloutVR.)
  215.  
  216.  
  217.  
  218. __shl = <function>
  219. --------------------------------------------------------------------------------
  220. http://www.lua.org/manual/5.4/manual.html#2.4
  221. This method runs when bitwise left shift is performed on the parent.
  222.  
  223. Usage: tab << n
  224. Function: __shl(self, n)
  225. Return: <any value>
  226.  
  227. (Not present in Lua 5.2 or lower.)
  228. (Currently not present in ComputerCraft.)
  229. (Currently not present in ChilloutVR.)
  230.  
  231.  
  232.  
  233. __shr = <function>
  234. --------------------------------------------------------------------------------
  235. http://www.lua.org/manual/5.4/manual.html#2.4
  236. This method runs when bitwise right shift is performed on the parent.
  237.  
  238. Usage: tab >> n
  239. Function: __shr(self, n)
  240. Return: <any value>
  241.  
  242. (Not present in Lua 5.2 or lower.)
  243. (Currently not present in ComputerCraft.)
  244. (Currently not present in ChilloutVR.)
  245.  
  246.  
  247.  
  248. +-----------+------------+
  249. | Operators | Comparison |
  250. +-----------+------------+
  251.  
  252.  
  253.  
  254. __eq = <function>
  255. --------------------------------------------------------------------------------
  256. http://www.lua.org/manual/5.4/manual.html#2.4
  257. This method runs when equality is performed on the parent and another table
  258. with the same metatable.
  259.  
  260. Usage: tab == tab2
  261. Function: __eq(self, tab2)
  262. Return: <boolean>
  263.  
  264. Don't use 'self ==' in the function. It will cause a stack overflow because it
  265. calls the comparison operator on itself, which calls __eq() again, which calls
  266. the comparison again, which calls the function again, etc. This also wouldn't
  267. return anything useful for this metamethod anyway.
  268. Instead use '==' on a property of self.
  269.  
  270.  
  271.  
  272. __lt = <function>
  273. --------------------------------------------------------------------------------
  274. http://www.lua.org/manual/5.4/manual.html#2.4
  275. This method runs when "less than" or "greater than" is performed on the parent
  276. and another table with the same metatable.
  277.  
  278. Usage: tab < tab2 or tab > tab2
  279. Function: __lt(self, tab2)
  280. Return: <boolean>
  281.  
  282. If greater than is used, the two tables are automatically swapped, so
  283. tab > tab2
  284. automatically becomes
  285. tab2 < tab
  286. which is why both tables need to be using the same metatable.
  287.  
  288. Don't use 'self <' or 'self >' in the function. It will cause a stack overflow
  289. because it calls the comparison operator on itself, which calls __lt() again,
  290. which calls the comparison again, which calls the function again, etc.
  291. This also wouldn't return anything useful for this metamethod anyway.
  292. Instead use '<' or '>' on a property of self.
  293.  
  294.  
  295.  
  296. __le = <function>
  297. --------------------------------------------------------------------------------
  298. http://www.lua.org/manual/5.4/manual.html#2.4
  299. This method runs when "less than or equal" or "greater than or equal" is
  300. performed on the parent and another table with the same metatable.
  301.  
  302. Usage: tab <= tab2 or tab >= tab2
  303. Function: __le(self, tab2)
  304. Return: <boolean>
  305.  
  306. If greater than or equal is used, the two tables are automatically swapped, so
  307. tab >= tab2
  308. automatically becomes
  309. tab2 <= tab
  310. which is why both tables need to be using the same metatable.
  311.  
  312. Don't use 'self <=' or 'self >=' in the function. It will cause a stack overflow
  313. because it calls the comparison operator on itself, which calls __le() again,
  314. which calls the comparison again, which calls the function again, etc.
  315. This also wouldn't return anything useful for this metamethod anyway.
  316. Instead use '<=' or '>=' on a property of self.
  317.  
  318.  
  319.  
  320. +-----------+-------+
  321. | Operators | Misc. |
  322. +-----------+-------+
  323.  
  324.  
  325.  
  326. __concat = <function>
  327. --------------------------------------------------------------------------------
  328. http://www.lua.org/manual/5.4/manual.html#2.4
  329. This method runs when concatenation is performed on the parent.
  330.  
  331. Usage: tab .. s
  332. Function: __concat(self, s)
  333. Return: <any value>
  334.  
  335.  
  336.  
  337. __len = <function>
  338. -------------------------------------------------------------------------------
  339. http://www.lua.org/manual/5.4/manual.html#2.4
  340. This method runs when getting the length/size of the table.
  341.  
  342. Usage: #tab
  343. Function: __len(self)
  344. Return: <any value>
  345.  
  346. Don't use #self in the function. It will cause a stack overflow because it calls
  347. the length of itself, which runs __len() again, which gets the length of itself
  348. again, which calls the function again, etc.
  349. Instead, create the table and metatable as seperate variables, then use __len to
  350. return the length of the parent, then use setmetatable() to put them
  351. together.
  352. Alternatively, you can get the length of a property of the parent table, a
  353. property of the metatable, or return a completely different value.
  354. This metamethod can only return a single value.
  355.  
  356.  
  357.  
  358. +----------+----------+
  359. | Behavior | Indexing |
  360. +----------+----------+
  361.  
  362.  
  363. __index = <any value>
  364. --------------------------------------------------------------------------------
  365. http://www.lua.org/manual/5.4/manual.html#2.4
  366. You can set this to any data type.
  367. The most useful way to use this is to set it as a table. For example:
  368.  
  369. tab = {a = 1}
  370. meta = {__index = {b = 2}}
  371. tab = setmetatable(tab, meta)
  372.  
  373. tab.a is completely exposed, it can be read and overwritten by the user.
  374. If you call tab.b it will return the 2 that's in the metatable.
  375. This value is read only. If you try to overwrite b by doing:
  376.  
  377. tab.b = 3
  378.  
  379. it will simply create 'b = 3' in the public table.
  380. The 'b' in the metatable will still be there, but you will not be able to read
  381. it with 'tab.b' anymore.
  382. To get full access to the contents of __index you have to use:
  383.  
  384. getmetatable(tab).__index
  385.  
  386. This exposes the metatable just like its public members.
  387.  
  388.  
  389.  
  390. __metatable = <any value>
  391. --------------------------------------------------------------------------------
  392. http://www.lua.org/manual/5.4/manual.html#pdf-getmetatable
  393. Use this metamethod to hide your metatable behind a facade.
  394. getmetatable(tab) will return __metatable instead of the real metatable, making
  395. the real one completely immutable.
  396. The real metatable becomes protected, and cannot be changed with setmetatable().
  397. __metatable is completely inaccessible without the use of getmetatable().
  398.  
  399. This metamethod can be of any type.
  400. The metamethod itself is completely immutable, however, if you set this to
  401. a table, you can manipulate the table by adding and changing elements.
  402. Setting this to nil would be the same as not setting it at all.
  403.  
  404.  
  405.  
  406. __newindex = <function>
  407. --------------------------------------------------------------------------------
  408. http://www.lua.org/manual/5.4/manual.html#2.4
  409. This method runs when elements in the parent are being added with 'table.insert'
  410. or with the assignment operator. It also runs when elements are being removed
  411. with 'table.remove'.
  412. One example of how to use this metamethod is to prevent new elements from being
  413. added to the parent table, like so:
  414.  
  415. __newindex = function(self, key, value)
  416. error("attempted to update a protected object", 2)
  417. end
  418.  
  419. 'self' is the parent table, 'key' is the key or index in the parent, 'value' is
  420. the value being assigned to the key or index. If you set this to an empty
  421. function, it will do absolutely nothing, including changing the table.
  422. This function does not prevent existing elements from being changed, including
  423. setting elements to 'nil' which removes them from the table.
  424.  
  425.  
  426.  
  427. +----------+---------+
  428. | Behavior | Calling |
  429. +----------+---------+
  430.  
  431.  
  432.  
  433. __call = <function>
  434. --------------------------------------------------------------------------------
  435. http://www.lua.org/manual/5.4/manual.html#2.4
  436. This method runs when a function call is performed on the parent.
  437.  
  438. Usage: tab(...)
  439. Function: __call(self, ...)
  440. Return: <any value>
  441.  
  442.  
  443.  
  444. __tostring = <function>
  445. --------------------------------------------------------------------------------
  446. This method runs when printing/writing the parent.
  447.  
  448. Usage: print(tab)
  449. Function: __tostring()
  450. Return: <any value>
  451.  
  452. When returning values, it only really works with strings, numbers, booleans and
  453. nil, and even then, strings are the only real use case.
  454.  
  455.  
  456.  
  457. +----------+-----------+
  458. | Behavior | Iteration |
  459. +----------+-----------+
  460.  
  461.  
  462.  
  463. __name = <string>
  464. --------------------------------------------------------------------------------
  465. http://www.lua.org/manual/5.4/manual.html#luaL_newmetatable
  466. Sets the name of the parent in Lua's registry.
  467. (I need help finding examples of how to use this metamethod.)
  468.  
  469.  
  470.  
  471. __pairs = <function>
  472. --------------------------------------------------------------------------------
  473. http://www.lua.org/manual/5.4/manual.html#pdf-pairs
  474. This metamethod is used for iterating over a table of any type of keys.
  475.  
  476. Usage: for i, v in pairs(tab) do ... end
  477. Function: __pairs = function(self) return next, self, nil end
  478.  
  479. The return values of this function are only used by the 'pairs' function and are
  480. never passed to the user except through the iterators and values of the for
  481. loop.
  482. The third value, 'nil' represents the key that the 'next' function starts
  483. with, which returns the key/value pair in the table. While it technically isn't
  484. necessary to write 'nil' here, it's kept to show the significance of the third
  485. value as you might want to start with an element other than the very first one.
  486. If you have elements in both the parent table and the '__index' table, you can
  487. iterate over both by doing something like this:
  488.  
  489. __pairs = function(self)
  490. local meta = getmetatable(self).__index
  491. local allkeys = {}
  492.  
  493. for _, t in pairs({self, meta})
  494. for k, v in next, t do
  495. allkeys[k] = v
  496. end
  497. end
  498.  
  499. return next, allkeys
  500. end
  501.  
  502. The 'next' function in the second for loop does basically the same thing as the
  503. 'pairs' function. We use it in this context because the 'pairs' function would
  504. cause a stack overflow error, due to the fact that 'pairs' runs this metamethod
  505. every time it's used on the parent, whereas 'next' doesn't.
  506.  
  507.  
  508.  
  509. __ipairs = <function>
  510. --------------------------------------------------------------------------------
  511. http://www.lua.org/manual/5.4/manual.html#pdf-ipairs
  512. This metamethod is used for iterating over a table of indicies.
  513.  
  514. Usage: for i, v in ipairs(tab) do ... end
  515. Function: __ipairs = function(self)
  516. local function iter(tbl, i)
  517. i = i + 1
  518. local v = tbl[i]
  519. if v ~= nil then return i, v end
  520. end
  521. return iter, self, 0
  522. end
  523.  
  524. This does the same thing as '__pairs', except it's for iterating over indecies
  525. in numerical order instead of all elements in an arbitrary order.
  526. (Doesn't work or is removed in Lua 5.3+ or ComputerCraft? Need confirmation.)
  527.  
  528.  
  529.  
  530. +----------+--------------------+
  531. | Behavior | Garbage Collection |
  532. +----------+--------------------+
  533.  
  534.  
  535.  
  536. __close
  537. --------------------------------------------------------------------------------
  538. http://www.lua.org/manual/5.4/manual.html#3.3.8
  539. This method marks a value to be released from memory as soon as it goes out of
  540. scope.
  541. (I need help finding examples of how to use this metamethod.)
  542.  
  543.  
  544.  
  545. __gc
  546. --------------------------------------------------------------------------------
  547. http://www.lua.org/manual/5.4/manual.html#2.5.3
  548. This method marks a value to be collected by the garbage collector.
  549. (I need help finding examples of how to use this metamethod.)
  550.  
  551.  
  552.  
  553. __mode = "k" or "v" or "kv"
  554. --------------------------------------------------------------------------------
  555. http://www.lua.org/manual/5.4/manual.html#2.5.4
  556. This method makes the table a "weak" table which means marking keys, values or
  557. both for garbage collection.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement