Advertisement
Guest User

Lua Cheat Sheet for Programmers

a guest
Oct 31st, 2010
5,783
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.16 KB | None | 0 0
  1. -- Lua Cheat Sheet for Programmers, by Al Sweigart http://coffeeghost.net
  2. -- This cheat sheet is an executable Lua program.
  3. --[[ This is
  4. a multline comment]]
  5.  
  6. ---[[ This is a neat trick. The first -- makes -[[ not a multiline comment.
  7. print("This line executes.")
  8. --]] The rest of this line is also a comment.
  9.  
  10. print("Here is a string" .. ' concatenated with ' .. 2 .. ' other strings.')
  11.  
  12. -- Note: All number types are doubles. There're no integers.
  13. print(type(42), type(42.0)) -- prints out "number  number"
  14. variable_one = 1 + 2 - 3 -- This will equal zero.
  15. variable_One = "Variables are case sensitive."
  16. negative_twofiftysix = -2^8
  17.  
  18. a, b = 42, 101 --mulitple assignment
  19. a, b = b, a    --provides a nice value swap trick
  20. x, y, z = 1, 2, 3, "this value is discarded"
  21.  
  22. print(previously_unused_variable == nil) -- prints true, all vars start as nil
  23. print(nil == 0 or nil == "") -- prints false, nil is not the same as false or 0
  24. print('The # len operator says there are ' .. #'hello' .. ' letters in "hello".')
  25.  
  26. some_bool_variable = true and false or true and not false
  27.  
  28. a_table = {['spam'] = "Type something in:", ['eggs'] = 10} -- tables are dictionaries/arrays
  29. print(a_table['spam'])
  30.  
  31. what_the_user_typed_in = io.read()
  32. print('You typed in ' .. what_the_user_typed_in)
  33.  
  34. if 10 < 20 then
  35.     print( "apple" == "orange" ) -- prints false
  36.     print( "apple" ~= "orange" ) -- true, an apple is not equal to an orange
  37.     local foo
  38.     foo = 42
  39.     print(foo)
  40. elseif 50 < 100 then
  41.     --These clauses can contain no lines of code.
  42. end
  43. print(foo) -- prints nil, local foo exists only in that "if" block above
  44.  
  45. m = 0
  46. while m < 10 do
  47.     print("howdy " .. m)
  48.     m = m + 1 -- there is no m++ or m += 1
  49.     repeat
  50.         print("Repeat loops check the condition at end, and stops if it is true.")
  51.         break -- breaks out of the loop early
  52.     until m == 9999
  53. end
  54.  
  55. for i = 1, 10 do
  56.     for j = 1, 10, 2 do
  57.         print("for loops add 1 to i and 2 to j each iteration " .. i .. ' ' .. j)
  58.     end
  59. end
  60.  
  61. function Greet(name)
  62.     print('Hello ' .. name)
  63.     bar = 100
  64.     return "returns nil if you don't have a return statement."
  65. end
  66. Greet('Al Sweigart')
  67. print(bar) -- prints 100
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement