OSDN Git Service

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