Advertisement
ItsNoah

lua cheetsheat

Feb 9th, 2023
883
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 12.47 KB | None | 0 0
  1. -- [[ Cheatsheet for LUA from http://www.newthinktank.com/2015/06/learn-lua-one-video/]]
  2.  
  3. -- Prints to the screen (Can end with semicolon)
  4. print("Hello World")
  5.  
  6. --[[
  7. Multiline comment
  8. ]]
  9.  
  10. -- Variable names can't start with a number, but can contain letters, numbers
  11. -- and underscores
  12.  
  13. -- Lua is dynamically typed based off of the data stored there
  14. -- This is a string and it can be surrounded by ' or "
  15. name = "Derek"
  16.  
  17. -- Another way to print to the screen
  18. -- Escape Sequences : \n \b \t \\ \" \'
  19. -- Get the string size by proceeding it with a #
  20. io.write("Size of string ", #name, "\n")
  21.  
  22. -- You can store any data type in a variable even after initialization
  23. name = 4
  24. io.write("My name is ", name, "\n")
  25.  
  26. -- Lua only has floating point numbers and this is the max number
  27. bigNum = 9223372036854775807 + 1
  28. io.write("Big Number ", bigNum, "\n")
  29.  
  30. io.write("Big Number ", type(bigNum), "\n")
  31.  
  32. -- Floats are precise up to 13 digits
  33. floatPrecision = 1.999999999999 + 0.0000000000005
  34. io.write(floatPrecision, "\n")
  35.  
  36. -- We can create long strings and maintain white space
  37. longString = [[
  38. I am a very very long
  39. string that goes on for
  40. ever]]
  41. io.write(longString, "\n")
  42.  
  43. -- Combine Strings with ..
  44. longString = longString .. name
  45. io.write(longString, "\n")
  46.  
  47. -- Booleans store with true or false
  48. isAbleToDrive = true
  49. io.write(type(isAbleToDrive), "\n")
  50.  
  51. -- Every variable gets the value of nil by default meaning it has no value
  52. io.write(type(madeUpVar), "\n")
  53.  
  54. -- ---------- MATH ----------
  55. io.write("5 + 3 = ", 5+3, "\n")
  56. io.write("5 - 3 = ", 5-3, "\n")
  57. io.write("5 * 3 = ", 5*3, "\n")
  58. io.write("5 / 3 = ", 5/3, "\n")
  59. io.write("5.2 % 3 = ", 5%3, "\n")
  60.  
  61. -- Shorthand like number++ and number += 1 aren't in Lua
  62.  
  63. -- Math Functions: floor, ceil, max, min, sin, cos, tan,
  64. -- asin, acos, exp, log, log10, pow, sqrt, random, randomseed
  65.  
  66. io.write("floor(2.345) : ", math.floor(2.345), "\n")
  67. io.write("ceil(2.345) : ", math.ceil(2.345), "\n")
  68. io.write("max(2, 3) : ", math.max(2, 3), "\n")
  69. io.write("min(2, 3) : ", math.min(2, 3), "\n")
  70. io.write("pow(8, 2) : ", math.pow(8, 2), "\n")
  71. io.write("sqrt(64) : ", math.sqrt(64), "\n")
  72.  
  73. -- Generate random number between 0 and 1
  74. io.write("math.random() : ", math.random(), "\n")
  75.  
  76. -- Generate random number between 1 and 10
  77. io.write("math.random(10) : ", math.random(10), "\n")
  78.  
  79. -- Generate random number between 1 and 100
  80. io.write("math.random(1,100) : ", math.random(1,100), "\n")
  81.  
  82. -- Used to set a seed value for random
  83. math.randomseed(os.time())
  84.  
  85. -- Print float to 10 decimals
  86. print(string.format("Pi = %.10f", math.pi))
  87.  
  88. -- ---------- CONDITIONALS ----------
  89. -- Relational Operators : > < >= <= == ~=
  90. -- Logical Operators : and or not
  91.  
  92. age = 13
  93.  
  94. if age < 16 then
  95.     io.write("You can go to school", "\n")
  96.     local localVar = 10
  97. elseif (age >= 16) and (age < 18) then
  98.     io.write("You can drive", "\n")
  99. else
  100.     io.write("You can vote", "\n")
  101. end
  102.  
  103. -- A variable marked local is local only to this if statement
  104. -- io.write("Local Variable : ", localvar)
  105.  
  106. if (age < 14) or (age > 67) then io.write("You shouldn't work\n") end
  107.  
  108. -- Format, convert to string and place boolean value with string.format
  109. print(string.format("not true = %s", tostring(not true)))
  110.  
  111. -- There is no ternary operator in Lua
  112. -- canVote = age > 18 ? true : false
  113.  
  114. -- This is similar to the ternary operator
  115. canVote = age > 18 and true or false
  116. io.write("Can I Vote : ", tostring(canVote), "\n")
  117.  
  118. -- There is no Switch statement in Lua
  119.  
  120. -- ---------- STRINGS ----------
  121. quote = "I changed my password everywhere to 'incorrect.' That way when I forget it,it always reminds me, 'Your password is incorrect.'"
  122.  
  123. io.write("Quote Length : ", string.len(quote), "\n")
  124.  
  125. -- Return the string after replacing
  126. io.write("Replace I with me : ", string.gsub(quote, "I", "me"), "\n")
  127.  
  128. -- Find the index of a matching String
  129. io.write("Index of password : ", string.find(quote, "password"), "\n")
  130.  
  131. -- Set characters to upper and lowercase
  132. io.write("Quote Upper : ", string.upper(quote), "\n")
  133. io.write("Quote Lower : ", string.lower(quote), "\n")
  134.  
  135. -- ---------- LOOPING ----------
  136. i = 1
  137. while (i <= 10) do
  138.   io.write(i)
  139.   i = i + 1
  140.  
  141.   -- break throws you out of a loop
  142.   -- continue doesn't exist with Lua
  143.   if i == 8 then break end
  144. end
  145. print("\n")
  146.  
  147. -- Repeat will cycle through the loop at least once
  148. repeat
  149.   io.write("Enter your guess : ")
  150.  
  151.   -- Gets input from the user
  152.   guess = io.read()
  153.  
  154.   -- Either surround the number with quotes, or convert the string into
  155.   -- a number
  156. until tonumber(guess) == 15
  157.  
  158. -- Value to start with, value to stop at, increment each loop
  159. for i = 1, 10, 1 do
  160.   io.write(i)
  161. end
  162.  
  163. print()
  164.  
  165. -- Create a table which is a list of items like an array
  166. months = {"January", "February", "March", "April", "May",
  167. "June", "July", "August", "September", "October", "November",
  168. "December"}
  169.  
  170. -- Cycle through table where k is the key and v the value of each item
  171. for k, v in pairs(months) do
  172.   io.write(v, " ")
  173. end
  174.  
  175. print()
  176.  
  177. -- ---------- TABLES ----------
  178. -- Tables take the place of arrays, dictionaries, tuples, etc.
  179.  
  180. -- Create a Table
  181. aTable = {}
  182.  
  183. -- Add values to a table
  184. for i = 1, 10 do
  185.   aTable[i] = i
  186. end
  187.  
  188. -- Access value by index
  189. io.write("First Item : ", aTable[1], "\n")
  190.  
  191. -- Items in Table
  192. io.write("Number of Items : ", #aTable, "\n")
  193.  
  194. -- Insert in table, at index, item to insert
  195. table.insert(aTable, 1, 0)
  196.  
  197. -- Combine a table as a String and seperate with provided seperator
  198. print(table.concat(aTable, ", "))
  199.  
  200. -- Remove item at index
  201. table.remove(aTable, 1)
  202. print(table.concat(aTable, ", "))
  203.  
  204. -- Sort items in reverse
  205. table.sort(aTable, function(a,b) return a>b end)
  206. print(table.concat(aTable, ", "))
  207.  
  208. -- Create a multidimensional Table
  209. aMultiTable = {}
  210.  
  211. for i = 0, 9 do
  212.   aMultiTable[i] = {}
  213.   for j = 0, 9 do
  214.     aMultiTable[i][j] = tostring(i) .. tostring(j)
  215.   end
  216. end
  217.  
  218. -- Access value in cell
  219. io.write("Table[0][0] : ", aMultiTable[1][2], "\n")
  220.  
  221. -- Cycle through and print a multidimensional Table
  222. for i = 0, 9 do
  223.   for j = 0, 9 do
  224.     io.write(aMultiTable[i][j], " : ")
  225.   end
  226.   print()
  227. end
  228.  
  229. -- ---------- FUNCTIONS ----------
  230. function getSum(num1, num2)
  231.   return num1 + num2
  232. end
  233.  
  234. print(string.format("5 + 2 = %d", getSum(5,2)))
  235.  
  236. function splitStr(theString)
  237.  
  238.   stringTable = {}
  239.   local i = 1
  240.  
  241.   -- Cycle through the String and store anything except for spaces
  242.   -- in the table
  243.   for str in string.gmatch(theString, "[^%s]+") do
  244.     stringTable[i] = str
  245.     i = i + 1
  246.   end
  247.  
  248.   -- Return multiple values
  249.   return stringTable, i
  250. end
  251.  
  252. -- Receive multiple values
  253. splitStrTable, numOfStr = splitStr("The Turtle")
  254.  
  255. for j = 1, numOfStr do
  256.   print(string.format("%d : %s", j, splitStrTable[j]))
  257. end
  258.  
  259. -- Variadic Function recieve unknown number of parameters
  260. function getSumMore(...)
  261.   local sum = 0
  262.  
  263.   for k, v in pairs{...} do
  264.     sum = sum + v
  265.   end
  266.   return sum
  267. end
  268.  
  269. io.write("Sum : ", getSumMore(1,2,3,4,5,6), "\n")
  270.  
  271. -- A function is a variable in that we can store them under many variable
  272. -- names as well as in tables and we can pass and return them though functions
  273.  
  274. -- Saving an anonymous function to a variable
  275. doubleIt = function(x) return x * 2 end
  276. print(doubleIt(4))
  277.  
  278. -- A Closure is a function that can access local variables of an enclosing
  279. -- function
  280. function outerFunc()
  281.   local i = 0
  282.   return function()
  283.     i = i + 1
  284.     return i
  285.   end
  286. end
  287.  
  288. -- When you include an inner function in a function that inner function
  289. -- will remember changes made on variables in the inner function
  290. getI = outerFunc()
  291. print(getI())
  292. print(getI())
  293.  
  294. -- ---------- COROUTINES ----------
  295. -- Coroutines are like threads except that they can't run in parallel
  296. -- A coroutine has the status of running, susepnded, dead or normal
  297.  
  298. -- Use create to create one that performs some action
  299. co = coroutine.create(function()
  300.   for i = 1, 10, 1 do
  301.   print(i)
  302.   print(coroutine.status(co))
  303.   if i == 5 then coroutine.yield() end
  304.   end end)
  305.  
  306. -- They start off with the status suspended
  307. print(coroutine.status(co))
  308.  
  309. -- Call for it to run with resume during which the status changes to running
  310. coroutine.resume(co)
  311.  
  312. -- After execution it has the status of dead
  313. print(coroutine.status(co))
  314.  
  315. co2 = coroutine.create(function()
  316.   for i = 101, 110, 1 do
  317.   print(i)
  318.   end end)
  319.  
  320. coroutine.resume(co2)
  321. coroutine.resume(co)
  322.  
  323. -- ---------- FILE I/O ----------
  324. -- Different ways to work with files
  325. -- r: Read only (default)
  326. -- w: Overwrite or create a new file
  327. -- a: Append or create a new file
  328. -- r+: Read & write existing file
  329. -- w+: Overwrite read or create a file
  330. -- a+: Append read or create file
  331.  
  332. -- Create new file for reading and writing
  333. file = io.open("test.lua", "w+")
  334.  
  335. -- Write text to the file
  336. file:write("Random string of text\n")
  337. file:write("Some more text\n")
  338.  
  339. -- Move back to the beginning of the file
  340. file:seek("set", 0)
  341.  
  342. -- Read from the file
  343. print(file:read("*a"))
  344.  
  345. -- Close the file
  346. file:close()
  347.  
  348. -- Open file for appending and reading
  349. file = io.open("test.lua", "a+")
  350.  
  351. file:write("Even more text\n")
  352.  
  353. file:seek("set", 0)
  354.  
  355. print(file:read("*a"))
  356.  
  357. file:close()
  358.  
  359. -- ---------- MODULES ----------
  360. -- A Module is like a library full of functions and variables
  361.  
  362. -- Use require to gain access to the functions in the module
  363. convertModule = require("convert")
  364.  
  365. -- Execute the function in the module
  366. print(string.format("%.3f cm", convertModule.ftToCm(12)))
  367.  
  368. -- ---------- METATABLES ----------
  369. -- Used to define how operations on tables should be carried out in regards
  370. -- to adding, subtracting, multiplying, dividing, concatenating, or
  371. -- comparing tables
  372.  
  373. -- Create a table and put default values in it
  374. aTable = {}
  375. for x = 1, 10 do
  376.   aTable[x] = x
  377. end
  378.  
  379. mt = {
  380.   -- Define how table values should be added
  381.   -- You can also define _sub, _mul, _div, _mod, _concat (..)
  382.   __add = function (table1, table2)
  383.  
  384.     sumTable = {}
  385.  
  386.     for y = 1, #table1 do
  387.       if (table1[y] ~= nil) and (table2[y] ~= nil) then
  388.         sumTable[y] = table1[y] + table2[y]
  389.       else
  390.         sumTable[y] = 0
  391.       end
  392.     end
  393.  
  394.     return sumTable
  395.   end,
  396.  
  397.   -- Define how table values should be checked for equality
  398.   __eq = function (table1, table2)
  399.     return table1.value == table2.value
  400.   end,
  401.  
  402.   -- For homework figure out how to check if less then
  403.   __lt = function (table1, table2)
  404.     return table1.value < table2.value
  405.   end,
  406.  
  407.   -- For homework figure out how to check if less then or equal
  408.   __le = function (table1, table2)
  409.     return table1.value <= table2.value
  410.   end,
  411. }
  412.  
  413. -- Attach the metamethods to this table
  414. setmetatable(aTable, mt)
  415.  
  416. -- Check if tables are equal
  417. print(aTable == aTable)
  418.  
  419. addTable = {}
  420.  
  421. -- Add values in tables
  422. addTable = aTable + aTable
  423.  
  424. -- print the results of the addition
  425. for z = 1, #addTable do
  426.   print(addTable[z])
  427. end
  428.  
  429. -- ---------- OBJECT ORIENTED PROGRAMMING ----------
  430. -- Lua is not an OOP language and it doesn't allow you to define classes
  431. -- but you can fake it using tables and metatables
  432.  
  433. -- Define the defaults for our table
  434. Animal = {height = 0, weight = 0, name = "No Name", sound = "No Sound"}
  435.  
  436. -- Used to initialize Animal objects
  437. function Animal:new (height, weight, name, sound)
  438.  
  439.   setmetatable({}, Animal)
  440.  
  441.   -- Self is a reference to values for this Animal
  442.   self.height = height
  443.   self.weight = weight
  444.   self.name = name
  445.   self.sound = sound
  446.  
  447.   return self
  448. end
  449.  
  450. -- Outputs a string that describes the Animal
  451. function Animal:toString()
  452.  
  453.   animalStr = string.format("%s weighs %.1f lbs, is %.1f in tall and says %s", self.name, self.weight, self.height, self.sound)
  454.  
  455.   return animalStr
  456. end
  457.  
  458. -- Create an Animal
  459. spot = Animal:new(10, 15, "Spot", "Roof")
  460.  
  461. -- Get variable values
  462. print(spot.weight)
  463.  
  464. -- Call a function in Animal
  465. print(spot:toString())
  466.  
  467. -- ---------- INHERITANCE ----------
  468. -- Extends the properties and functions in another object
  469.  
  470. Cat = Animal:new()
  471.  
  472. function Cat:new (height, weight, name, sound, favFood)
  473.   setmetatable({}, Cat)
  474.  
  475.   -- Self is a reference to values for this Animal
  476.   self.height = height
  477.   self.weight = weight
  478.   self.name = name
  479.   self.sound = sound
  480.   self.favFood = favFood
  481.  
  482.   return self
  483. end
  484.  
  485. -- Overide an Animal function
  486. function Cat:toString()
  487.  
  488.   catStr = string.format("%s weighs %.1f lbs, is %.1f in tall, says %s and loves %s", self.name, self.weight, self.height, self.sound, self.favFood)
  489.  
  490.   return catStr
  491. end
  492.  
  493. -- Create a Cat
  494. fluffy = Cat:new(10, 15, "Fluffy", "Meow", "Tuna")
  495.  
  496. print(fluffy:toString())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement