···11-# lua-cheatsheet
22- a simple cheatsheet for lua
11+# du-lua-cheatsheet
22+ a simple cheatsheet for lua in Dual Universe
33+44+## Menu
55+66+* [Comments](#comments)
77+* [invoking functions](#invoking-functions)
88+* [Tables / arrays](#tables--arrays)
99+* [Loops](#loops)
1010+* [Conditions](#conditions)
1111+* [variables](#variables)
1212+* [Functions](#functions)
1313+* [Lookups](#lookups)
1414+* [Metatables](#metatables)
1515+* [classes](#classes)
1616+* [constants](#constants)
1717+* [operators and thei metatable names](#operators-and-thei-metatable-names)
1818+* [API Global Functions](#api-global-functions)
1919+* [API Strings](#api-strings)
2020+* [Coroutine](#coroutine)
2121+2222+# Lua Cheatsheet
2323+2424+## Comments
2525+2626+```lua
2727+-- comment
2828+2929+--[[
3030+ multiline
3131+ comment
3232+]]
3333+```
3434+3535+## invoking functions
3636+3737+```lua
3838+system.print()
3939+system.print("Hi")
4040+4141+-- You can omit parentheses if the argument is one string or table literal
4242+system.print "Hello World" <-> system.print("Hello World")
4343+f{x=10, y=20} <-> f({x=10, y=20})
4444+type{} <-> type({})
4545+```
4646+4747+## Tables / arrays
4848+4949+```lua
5050+t = {}
5151+t = { a = 1, b = 2 }
5252+t.a = function() ... end
5353+5454+t = { ["hello"] = 200 }
5555+t.hello
5656+5757+-- Remember, arrays are also tables
5858+array = { "a", "b", "c", "d" }
5959+system.print(array[2]) -- "b" (one-indexed)
6060+system.print(#array) -- 4 (length)
6161+6262+6363+-- API functions
6464+table.foreach(t, function(row) ... end) -- Iterates over the table
6565+table.setn(t, 10) -- Sets the length of the table
6666+table.insert(t, 21) -- append (--> t[#t+1] = 21)
6767+table.insert(t, 4, 99) -- insert (--> t[4] = 99)
6868+table.getn(t) -- length (--> #t)
6969+table.concat(t, ", ") -- join (--> "a, b, c, d")
7070+table.sort(t) -- sort (--> { "a", "b", "c", "d" }
7171+table.sort(t, function(a,b) return a > b end) -- sort (--> { "d", "c", "b", "a" }
7272+table.remove(t, 4) -- remove (--> "d")
7373+```
7474+7575+## Loops
7676+7777+```lua
7878+while condition do
7979+end
8080+8181+for i = 1,5 do
8282+end
8383+8484+for i = start,finish,delta do
8585+end
8686+8787+for k,v in pairs(tab) do
8888+end
8989+9090+repeat
9191+until condition
9292+9393+-- Breaking out:
9494+while x do
9595+ if condition then break end
9696+end
9797+```
9898+9999+## Conditions
100100+101101+```lua
102102+if condition then
103103+ system.print("yes")
104104+elseif condition then
105105+ system.print("maybe")
106106+else
107107+ system.print("no")
108108+end
109109+```
110110+111111+# variables
112112+113113+```lua
114114+local x = 2
115115+two = 2
116116+two, four = 2, 4
117117+```
118118+119119+## Functions
120120+121121+```lua
122122+function myFunction()
123123+ return 1
124124+end
125125+126126+function myFunctionWithArgs(a, b)
127127+ -- ...
128128+end
129129+130130+myFunction()
131131+132132+anonymousFunctions(function()
133133+ -- ...
134134+end)
135135+136136+-- Not exported in the module
137137+local function myPrivateFunction()
138138+end
139139+140140+-- Splats
141141+function doAction(action, ...)
142142+ system.print("Doing '"..action.."' to", ...) -- "Doing 'write' to", "Shirley", "Abed"
143143+end
144144+145145+doAction('write', "Shirley", "Abed")
146146+```
147147+148148+## Lookups
149149+150150+```lua
151151+mytable = { x = 2, y = function() .. end }
152152+153153+-- The same:
154154+mytable.x
155155+mytable['x']
156156+157157+-- Syntactic sugar, these are equivalent:
158158+mytable.y(mytable)
159159+mytable:y()
160160+161161+mytable.y(mytable, a, b)
162162+mytable:y(a, b)
163163+164164+function X:y(z) .. end
165165+function X.y(self, z) .. end
166166+```
167167+168168+-- Metatables
169169+170170+```lua
171171+mt = {}
172172+173173+-- A metatable is simply a table with functions in it.
174174+mt.__tostring = function() return "lol" end
175175+mt.__add = function(b) ... end -- a + b
176176+mt.__mul = function(b) ... end -- a * b
177177+mt.__index = function(k) ... end -- Lookups (a[k] or a.k)
178178+mt.__newindex = function(k, v) ... end -- Setters (a[k] = v)
179179+180180+-- Metatables allow you to override behavior of another table.
181181+mytable = {}
182182+setmetatable(mytable, mt)
183183+184184+system.print(myobject)
185185+```
186186+187187+## classes
188188+189189+```lua
190190+-- A class is simply a table with a metatable.
191191+-- The metatable is used to create new instances of the class.
192192+-- The metatable's __index is used to lookup methods on the class.
193193+194194+-- Create a new class
195195+Account = {}
196196+197197+function Account:new(balance)
198198+ local t = setmetatable({}, { __index = Account })
199199+200200+ -- Your constructor stuff
201201+ t.balance = (balance or 0)
202202+ return t
203203+end
204204+205205+function Account:withdraw(amount)
206206+ print("Withdrawing "..amount.."...")
207207+ self.balance = self.balance - amount
208208+ self:report()
209209+end
210210+211211+function Account:report()
212212+ system.print("Your current balance is: "..self.balance)
213213+end
214214+215215+a = Account:new(9000)
216216+a:withdraw(200) -- method call
217217+218218+```
219219+220220+## constants
221221+222222+```lua
223223+nil
224224+false
225225+true
226226+```
227227+228228+## operators and thei metatable names
229229+230230+```lua
231231+-- Relational (binary)
232232+-- __eq __lt __gt __le __ge
233233+ == < > <= >=
234234+~= -- Not equal, just like !=
235235+236236+-- Arithmetic (binary)
237237+-- __add __sub __muv __div __mod __pow
238238+ + - * / % ^
239239+240240+-- Arithmetic (unary)
241241+-- __unm (unary minus)
242242+ -
243243+244244+-- Logic (and/or)
245245+nil and false --> nil
246246+false and nil --> false
247247+0 and 20 --> 20
248248+10 and 20 --> 20
249249+250250+251251+-- Length
252252+-- __len(array)
253253+#array
254254+255255+256256+-- Indexing
257257+-- __index(table, key)
258258+t[key]
259259+t.key
260260+261261+-- __newindex(table, key, value)
262262+t[key]=value
263263+264264+-- String concat
265265+-- __concat(left, right)
266266+"hello, "..name
267267+268268+-- Call
269269+-- __call(func, ...)
270270+```
271271+272272+## API Global Functions
273273+274274+```lua
275275+assert(x) -- Throws an error if x is false
276276+assert(x, "failed") -- Throws an error if x is false, with the message "failed"
277277+278278+type(x) -- Returns the type of x ("nil" | "number" | "string" | "boolean" | "table" | "function" | "thread")
279279+280280+-- Does /not/ invoke meta methods (__index and __newindex)
281281+rawset(t, index, value) -- Like t[index] = value
282282+rawget(t, index) -- Like t[index]
283283+284284+_G -- Global context
285285+setfenv(1, {}) -- 1: current function, 2: caller, and so on -- {}: the new _G
286286+287287+pairs(t) -- iterable list of {key, value}
288288+ipairs(t) -- iterable list of {index, value}
289289+290290+tonumber("34") -- 34
291291+tonumber("8f", 16) -- 143
292292+```
293293+294294+## API: Strings
295295+296296+```lua
297297+'string'..'concatenation' -- "stringconcatenation"
298298+299299+s = "Hello"
300300+s:upper() -- Just like string.upper(s): "HELLO"
301301+s:lower() -- Just like string.lower(s): "hello"
302302+s:len() -- Just like #s or string.len(s): 5
303303+304304+s:find("e") -- Just like string.find(s, "e"): 2 index (in lua index start ar 1, not 0) or nil if not found
305305+s:gfind("l") -- Just like string.gfind(s, "l"): iterator of all "l" in s or nil if not found
306306+307307+s:match("e") -- Just like string.match(s, "e"): "e" or nil if not found
308308+s:gmatch("l") -- Just like string.gmatch(s, "l"): iterator of all "l" in s or nil if not found
309309+310310+s:sub(2, 4) -- Just like string.sub(s, 2, 4): "ell"
311311+s:gsub("l", "i", 10) -- Just like string.gsub(s, "l", "i", 10): "Heiio" (10 is the number of replacement)
312312+313313+s:rep(10) -- Just like string.rep(s, 10): "HelloHelloHelloHelloHelloHelloHelloHelloHelloHello"
314314+s:char(65) -- Just like string.char(65): "A"
315315+s:reverse() -- Just like string.reverse(s): "olleH"
316316+s:byte() -- Just like string.byte(s): 72 (the first byte of the string)
317317+s:format("%s world") -- Just like string.format("%s world", s): "Hello world"
318318+```
319319+320320+## Coroutine
321321+322322+```lua
323323+-- A coroutine is a function that can be paused and resumed.
324324+-- It is useful for implementing cooperative multitasking.
325325+326326+-- Create a new coroutine
327327+co = coroutine.create(function() --[[do something]] end)
328328+329329+-- Resume a coroutine
330330+coroutine.resume(co) -- true | false, error
331331+332332+-- Yield a coroutine
333333+coroutine.yield()
334334+335335+-- Get the status of a coroutine
336336+coroutine.status(co) -- "running" | "suspended" | "dead"
337337+338338+-- example
339339+co = coroutine.create(function()
340340+ for i = 1, 10 do
341341+ system.print(i) -- print 1 to 10
342342+ coroutine.yield() -- pause
343343+ end
344344+end)
345345+346346+coroutine.resume(co) -- 1
347347+coroutine.resume(co) -- 2
348348+coroutine.resume(co) -- 3
349349+coroutine.resume(co) -- 4
350350+coroutine.resume(co) -- 5
351351+-- ...
352352+353353+```