OSDN Git Service

Regular updates
[twpd/master.git] / lua.md
1 ---
2 title: Lua
3 ---
4
5 ## Comments
6
7     -- comment
8     --[[ Multiline
9          comment ]]
10
11 ## Invoking functions
12
13     print()
14     print("Hi")
15
16     -- You can omit parentheses if the argument is one string or table literal
17     print "Hello World"     <-->     print("Hello World")
18     dofile 'a.lua'          <-->     dofile ('a.lua')
19     print [[a multi-line    <-->     print([[a multi-line
20      message]]                        message]])
21     f{x=10, y=20}           <-->     f({x=10, y=20})
22     type{}                  <-->     type({})
23
24 ## Tables / arrays
25
26     t = {}
27     t = { a = 1, b = 2 }
28     t.a = function() ... end
29
30     t = { ["hello"] = 200 }
31     t.hello
32
33     -- Remember, arrays are also tables
34     array = { "a", "b", "c", "d" }
35     print(array[2])       -- "b" (one-indexed)
36     print(#array)         -- 4 (length)
37
38 ## Loops
39
40     while condition do
41     end
42
43     for i = 1,5 do
44     end
45
46     for i = start,finish,delta do
47     end
48
49     for k,v in pairs(tab) do
50     end
51
52     repeat
53     until condition
54
55     -- Breaking out:
56     while x do
57       if condition then break end
58     end
59
60 ## Conditionals
61
62     if condition then
63       print("yes")
64     elseif condition then
65       print("maybe")
66     else
67       print("no")
68     end
69
70 ## Variables
71
72     local x = 2
73     two, four = 2, 4
74
75 ## Functions
76
77     function myFunction()
78       return 1
79     end
80
81     function myFunctionWithArgs(a, b)
82       -- ...
83     end
84
85     myFunction()
86
87     anonymousFunctions(function()
88       -- ...
89     end)
90
91     -- Not exported in the module
92     local function myPrivateFunction()
93     end
94
95     -- Splats
96     function doAction(action, ...)
97       print("Doing '"..action.."' to", ...)
98       --> print("Doing 'write' to", "Shirley", "Abed")
99     end
100
101     doAction('write', "Shirley", "Abed")
102
103 ## Lookups
104
105     mytable = { x = 2, y = function() .. end }
106
107     -- The same:
108     mytable.x
109     mytable['x']
110
111     -- Syntactic sugar, these are equivalent:
112     mytable.y(mytable)
113     mytable:y()
114
115     mytable.y(mytable, a, b)
116     mytable:y(a, b)
117
118     function X:y(z) .. end
119     function X.y(self, z) .. end
120
121 ## Metatables
122
123
124     mt = {}
125
126     -- A metatable is simply a table with functions in it.
127     mt.__tostring = function() return "lol" end
128     mt.__add      = function(b) ... end       -- a + b
129     mt.__mul      = function(b) ... end       -- a * b
130     mt.__index    = function(k) ... end       -- Lookups (a[k] or a.k)
131     mt.__newindex = function(k, v) ... end    -- Setters (a[k] = v)
132
133     -- Metatables allow you to override behavior of another table.
134     mytable = {}
135     setmetatable(mytable, mt)
136
137     print(myobject)
138
139 ## Classes
140
141     Account = {}
142
143     function Account:new(balance)
144       local t = setmetatable({}, { __index = Account })
145
146       -- Your constructor stuff
147       t.balance = (balance or 0)
148       return t
149     end
150
151     function Account:withdraw(amount)
152       print("Withdrawing "..amount.."...")
153       self.balance = self.balance - amount
154       self:report()
155     end
156
157     function Account:report()
158       print("Your current balance is: "..self.balance)
159     end
160
161     a = Account:new(9000)
162     a:withdraw(200)    -- method call
163
164 ## Constants
165
166     nil
167     false
168     true
169
170 ## Operators (and their metatable names)
171
172     -- Relational (binary)
173     -- __eq  __lt  __gt  __le  __ge
174        ==    <     >     <=    >=
175     ~=   -- Not equal, just like !=
176
177     -- Arithmetic (binary)
178     -- __add  __sub  __muv  __div  __mod  __pow
179        +      -      *      /      %      ^
180
181     -- Arithmetic (unary)
182     -- __unm (unary minus)
183        -
184
185     -- Logic (and/or)
186     nil and false  --> nil
187     false and nil  --> false
188     0 and 20       --> 20
189     10 and 20      --> 20
190
191
192     -- Length
193     -- __len(array)
194     #array
195
196
197     -- Indexing
198     -- __index(table, key)
199     t[key]
200     t.key
201
202     -- __newindex(table, key, value)
203     t[key]=value
204
205     -- String concat
206     -- __concat(left, right)
207     "hello, "..name
208
209     -- Call
210     -- __call(func, ...)
211
212
213 ## API: Global functions  [(ref)](http://lua.gts-stolberg.de/en/Basis.php)
214
215     dofile("hello.lua")
216     loadfile("hello.lua")
217
218     assert(x)    -- x or (raise an error)
219     assert(x, "failed")
220
221     type(var)   -- "nil" | "number" | "string" | "boolean" | "table" | "function" | "thread" | "userdata"
222
223     -- Does /not/ invoke meta methods (__index and __newindex)
224     rawset(t, index, value)    -- Like t[index] = value
225     rawget(t, index)           -- Like t[index]
226
227     _G  -- Global context
228     setfenv(1, {})  -- 1: current function, 2: caller, and so on -- {}: the new _G
229
230     pairs(t)     -- iterable list of {key, value}
231     ipairs(t)    -- iterable list of {index, value}
232
233     tonumber("34")
234     tonumber("8f", 16)
235
236 ## API: Strings
237
238     'string'..'concatenation'
239
240     s = "Hello"
241     s:upper()
242     s:lower()
243     s:len()    -- Just like #s
244
245     s:find()
246     s:gfind()
247
248     s:match()
249     s:gmatch()
250
251     s:sub()
252     s:gsub()
253
254     s:rep()
255     s:char()
256     s:dump()
257     s:reverse()
258     s:byte()
259     s:format()
260
261 ## API: Tables
262
263     table.foreach(t, function(row) ... end)
264     table.setn
265     table.insert(t, 21)          -- append (--> t[#t+1] = 21)
266     table.insert(t, 4, 99)
267     table.getn
268     table.concat
269     table.sort
270     table.remove(t, 4)
271
272 ## API: Math [(ref)](http://lua-users.org/wiki/MathLibraryTutorial)
273
274     math.abs     math.acos    math.asin       math.atan    math.atan2
275     math.ceil    math.cos     math.cosh       math.deg     math.exp
276     math.floor   math.fmod    math.frexp      math.ldexp   math.log
277     math.log10   math.max     math.min        math.modf    math.pow
278     math.rad     math.random  math.randomseed math.sin     math.sinh
279     math.sqrt    math.tan     math.tanh
280
281     math.sqrt(144)
282     math
283
284 ## API: Misc
285
286     io.output(io.open("file.txt", "w"))
287     io.write(x)
288     io.close()
289
290     for line in io.lines("file.txt")
291
292     file = assert(io.open("file.txt", "r"))
293     file:read()
294     file:lines()
295     file:close()
296
297 ## Reference
298
299   http://www.lua.org/pil/13.html
300   http://lua-users.org/wiki/ObjectOrientedProgramming