Learn Lua in 15 Minutes 整理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146


Learn Lua in 15 Minutes

more or less


-- Two dashes start a one-line comment.


--[[

     Adding two ['s and ]'s makes it a

     multi-line comment.

--]]


----------------------------------------------------

-- 1. Variables and flow control.

----------------------------------------------------


num = 42  -- All numbers are doubles.

-- Don't freak out, 64-bit doubles have 52 bits for

-- storing exact int values; machine precision is

-- not a problem for ints that need < 52 bits.


s = 'walternate'  -- Immutable strings like Python.

t = "double-quotes are also fine"

u = [[ Double brackets

       start and end

       multi-line strings.]]

t = nil  -- Undefines t; Lua has garbage collection.


-- Blocks are denoted with keywords like do/end:

while num < 50 do

  num = num + 1  -- No ++ or += type operators.

end


-- If clauses:

if num > 40 then

  print('over 40')

elseif s ~= 'walternate' then  -- ~= is not equals.

  -- Equality check is == like Python; ok for strs.

  io.write('not over 40\n'-- Defaults to stdout.

else

  -- Variables are global by default.

  thisIsGlobal = 5  -- Camel case is common.


  -- How to make a variable local:

  local line = io.read()  -- Reads next stdin line.


  -- String concatenation uses the .. operator:

  print('Winter is coming, ' .. line)

end


-- Undefined variables return nil.

-- This is not an error:

foo = anUnknownVariable  -- Now foo = nil.


aBoolValue = false


-- Only nil and false are falsy; 0 and '' are true!

if not aBoolValue then print('twas false') end


-- 'or' and 'and' are short-circuited.

-- This is similar to the a?b:c operator in C/js:

ans = aBoolValue and 'yes' or 'no'  --> 'no'


karlSum = 0

for i = 1, 100 do  -- The range includes both ends.

  karlSum = karlSum + i

end


-- Use "100, 1, -1" as the range to count down:

fredSum = 0

for j = 100, 1, -1 do fredSum = fredSum + j end


-- In general, the range is begin, end[, step].


-- Another loop construct:

repeat

  print('the way of the future')

  num = num - 1

until num == 0



----------------------------------------------------

-- 2. Functions.

----------------------------------------------------


function fib(n)

  if n < 2 then return 1 end

  return fib(n - 2) + fib(n - 1)

end


-- Closures and anonymous functions are ok:

function adder(x)

  -- The returned function is created when adder is

  -- called, and remembers the value of x:

  return function (y) return x + y end

end

a1 = adder(9)

a2 = adder(36)

print(a1(16))  --> 25

print(a2(64))  --> 100


-- Returns, func calls, and assignments all work

-- with lists that may be mismatched in length.

-- Unmatched receivers are nil;

-- unmatched senders are discarded.


x, y, z = 1, 2, 3, 4

-- Now x = 1, y = 2, z = 3, and 4 is thrown away.


function bar(a, b, c)

  print(a, b, c)

  return 4, 8, 15, 16, 23, 42

end


x, y = bar('zaphod'--> prints "zaphod  nil nil"

-- Now x = 4, y = 8, values 15..42 are discarded.


-- Functions are first-class, may be local/global.

-- These are the same:

function f(x) return x * x end

f = function (x) return x * x end


-- And so are these:

local function g(x) return math.sin(x) end

local g; g  = function (x) return math.sin(x) end

-- the 'local g' decl makes g-self-references ok.


-- Trig funcs work in radians, by the way.


-- Calls with one string param don't need parens:

print 'hello'  -- Works fine.



----------------------------------------------------

-- 3. Tables.

----------------------------------------------------


-- Tables = Lua's only compound data structure;

--          they are associative arrays.

-- Similar to php arrays or js objects, they are

-- hash-lookup dicts that can also be used as lists.


-- Using tables as dictionaries / maps:


-- Dict literals have string keys by default:

t = {key1 = 'value1', key2 = false}


-- String keys can use js-like dot notation:

print(t.key1)  -- Prints 'value1'.

t.newKey = {}  -- Adds a new key/value pair.

t.key2 = nil   -- Removes key2 from the table.


-- Literal notation for any (non-nil) value as key:

u = {['@!#'] = 'qbert', [{}] = 1729, [6.28] = 'tau'}

print(u[6.28])  -- prints "tau"


-- Key matching is basically by value for numbers

-- and strings, but by identity for tables.

a = u['@!#'-- Now a = 'qbert'.

b = u[{}]     -- We might expect 1729, but it's nil:

-- b = nil since the lookup fails. It fails

-- because the key we used is not the same object

-- as the one used to store the original value. So

-- strings & numbers are more portable keys.


-- A one-table-param function call needs no parens:

function h(x) print(x.key1) end

h{key1 = 'Sonmi~451'-- Prints 'Sonmi~451'.


for key, val in pairs(u) do  -- Table iteration.

  print(key, val)

end


-- _G is a special table of all globals.

print(_G['_G'] == _G-- Prints 'true'.


-- Using tables as lists / arrays:


-- List literals implicitly set up int keys:

v = {'value1', 'value2', 1.21, 'gigawatts'}

for i = 1, #v do  -- #v is the size of v for lists.

  print(v[i])  -- Indices start at 1 !! SO CRAZY!

end

-- A 'list' is not a real type. v is just a table

-- with consecutive integer keys, treated as a list.


----------------------------------------------------

-- 3.1 Metatables and metamethods.

----------------------------------------------------


-- A table can have a metatable that gives the table

-- operator-overloadish behavior. Later we'll see

-- how metatables support js-prototypey behavior.


f1 = {a = 1, b = 2-- Represents the fraction a/b.

f2 = {a = 2, b = 3}


-- This would fail:

-- s = f1 + f2


metafraction = {}

function metafraction.__add(f1, f2)

  sum = {}

  sum.b = f1.b * f2.b

  sum.a = f1.a * f2.b + f2.a * f1.b

  return sum

end


setmetatable(f1, metafraction)

setmetatable(f2, metafraction)


s = f1 + f2  -- call __add(f1, f2) on f1's metatable


-- f1, f2 have no key for their metatable, unlike

-- prototypes in js, so you must retrieve it as in

-- getmetatable(f1). The metatable is a normal table

-- with keys that Lua knows about, like __add.


-- But the next line fails since s has no metatable:

-- t = s + s

-- Class-like patterns given below would fix this.


-- An __index on a metatable overloads dot lookups:

defaultFavs = {animal = 'gru', food = 'donuts'}

myFavs = {food = 'pizza'}

setmetatable(myFavs, {__index = defaultFavs})

eatenBy = myFavs.animal  -- works! thanks, metatable


-- Direct table lookups that fail will retry using

-- the metatable's __index value, and this recurses.


-- An __index value can also be a function(tbl, key)

-- for more customized lookups.


-- Values of __index,add, .. are called metamethods.

-- Full list. Here a is a table with the metamethod.


-- __add(a, b)                     for a + b

-- __sub(a, b)                     for a - b

-- __mul(a, b)                     for a * b

-- __div(a, b)                     for a / b

-- __mod(a, b)                     for a % b

-- __pow(a, b)                     for a ^ b

-- __unm(a)                        for -a

-- __concat(a, b)                  for a .. b

-- __len(a)                        for #a

-- __eq(a, b)                      for a == b

-- __lt(a, b)                      for a < b

-- __le(a, b)                      for a <= b

-- __index(a, b)  <fn or a table>  for a.b

-- __newindex(a, b, c)             for a.b = c

-- __call(a, ...)                  for a(...)


----------------------------------------------------

-- 3.2 Class-like tables and inheritance.

----------------------------------------------------


-- Classes aren't built in; there are different ways

-- to make them using tables and metatables.


-- Explanation for this example is below it.


Dog = {}                                   -- 1.


function Dog:new()                         -- 2.

  newObj = {sound = 'woof'}                -- 3.

  self.__index = self                      -- 4.

  return setmetatable(newObj, self)        -- 5.

end


function Dog:makeSound()                   -- 6.

  print('I say ' .. self.sound)

end


mrDog = Dog:new()                          -- 7.

mrDog:makeSound()  -- 'I say woof'         -- 8.


-- 1. Dog acts like a class; it's really a table.

-- 2. function tablename:fn(...) is the same as

--    function tablename.fn(self, ...)

--    The : just adds a first arg called self.

--    Read 7 & 8 below for how self gets its value.

-- 3. newObj will be an instance of class Dog.

-- 4. self = the class being instantiated. Often

--    self = Dog, but inheritance can change it.

--    newObj gets self's functions when we set both

--    newObj's metatable and self's __index to self.

-- 5. Reminder: setmetatable returns its first arg.

-- 6. The : works as in 2, but this time we expect

--    self to be an instance instead of a class.

-- 7. Same as Dog.new(Dog), so self = Dog in new().

-- 8. Same as mrDog.makeSound(mrDog); self = mrDog.


----------------------------------------------------


-- Inheritance example:


LoudDog = Dog:new()                           -- 1.


function LoudDog:makeSound()

  s = self.sound .. ' '                       -- 2.

  print(s .. s .. s)

end


seymour = LoudDog:new()                       -- 3.

seymour:makeSound()  -- 'woof woof woof'      -- 4.


-- 1. LoudDog gets Dog's methods and variables.

-- 2. self has a 'sound' key from new(), see 3.

-- 3. Same as LoudDog.new(LoudDog), and converted to

--    Dog.new(LoudDog) as LoudDog has no 'new' key,

--    but does have __index = Dog on its metatable.

--    Result: seymour's metatable is LoudDog, and

--    LoudDog.__index = LoudDog. So seymour.key will

--    = seymour.key, LoudDog.key, Dog.key, whichever

--    table is the first with the given key.

-- 4. The 'makeSound' key is found in LoudDog; this

--    is the same as LoudDog.makeSound(seymour).


-- If needed, a subclass's new() is like the base's:

function LoudDog:new()

  newObj = {}

  -- set up newObj

  self.__index = self

  return setmetatable(newObj, self)

end


----------------------------------------------------

-- 4. Modules.

----------------------------------------------------



--[[ I'm commenting out this section so the rest of

--   this script remains runnable.

-- Suppose the file mod.lua looks like this:

local M = {}


local function sayMyName()

  print('Hrunkner')

end


function M.sayHello()

  print('Why hello there')

  sayMyName()

end


return M


-- Another file can use mod.lua's functionality:

local mod = require('mod'-- Run the file mod.lua.


-- require is the standard way to include modules.

-- require acts like:     (if not cached; see below)

local mod = (function ()

  <contents of mod.lua>

end)()

-- It's like mod.lua is a function body, so that

-- locals inside mod.lua are invisible outside it.


-- This works because mod here = M in mod.lua:

mod.sayHello()  -- Says hello to Hrunkner.


-- This is wrong; sayMyName only exists in mod.lua:

mod.sayMyName()  -- error


-- require's return values are cached so a file is

-- run at most once, even when require'd many times.


-- Suppose mod2.lua contains "print('Hi!')".

local a = require('mod2'-- Prints Hi!

local b = require('mod2'-- Doesn't print; a=b.


-- dofile is like require without caching:

dofile('mod2'--> Hi!

dofile('mod2'--> Hi! (runs again, unlike require)


-- loadfile loads a lua file but doesn't run it yet.

f = loadfile('mod2'-- Calling f() runs mod2.lua.


-- loadstring is loadfile for strings.

g = loadstring('print(343)'-- Returns a function.

g()  -- Prints out 343; nothing printed before now.


--]]


----------------------------------------------------

-- 5. References.

----------------------------------------------------


--[[


I was excited to learn Lua so I could make games

with the Löve 2D game engine. That's the why.


I started with BlackBulletIV's Lua for programmers.

Next I read the official Programming in Lua book.

That's the how.


It might be helpful to check out the Lua short

reference on lua-users.org.


The main topics not covered are standard libraries:

 * string library

 * table library

 * math library

 * io library

 * os library


By the way, this entire file is valid Lua; save it

as learn.lua and run it with "lua learn.lua" !


This was first written for tylerneylon.com. It's

also available as a github gist. Tutorials for other

languages, in the same style as this one, are here:


http://learnxinyminutes.com/


Have fun with Lua!


--]]




-- 注释语句
 
--[[ 
注释段落语句
   ]] --
 
--引用其他lua文件,不需要加上(.lua)后缀
--require "xx"
 
--变量不需要定义,可以直接赋值
count = 100  --成员变量
local count = 100  --局部变量
 
--方法定义
function hello ( ... )
     --打印
     print ( "Hello Lua!" ) ;
     print ( string .format ( ... ) )
end
 
-- 每一行代码不需要使用分隔符,当然也可以加上
-- 访问没有初始化的变量,lua默认返回nil
 
-- 调用函数形式
hello ( "你懂的" )
 
--打印变量的类型
isOK = false
print ( type ( isOK ) )
 
-- 基本变量类型
a = nil --Lua 中值为nil 相当于删除
b = 10
c = 10.4
d = false
--定义字符串,单引号,双引号都可以的
e = "i am"
d = 'himi'
 
--两个字符串的连接可以如下形式
stringA = "Hi"
stringB = "mi"
print ( stringA..stringB )
 
--另外Lua也支持转移字符,如下
print ( stringA.. "\n" ..stringB ) ;
 
--修改字符串的部分gsub,可以如下形式:(将stringA字符串中的Hi修改为WT)
stringA = string .gsub ( stringA , "Hi" , "WT" )
print ( stringA ) ;
 
--将字符换成数字tonumber(不转也会自动转)
--将数字换成字符tostring(不转也会自动转)
stringC = "100"
stringC = tonumber ( stringC )
stringC = stringC + 20
stringC = tostring ( stringC )
print ( stringC )
 
--取一个字符串的长度使用 #
print ( #stringC)
 
--创建 表
tableA = { }
m = "x"
tableA[m] = 100
m 2 = 'y'
tableA[m 2 ] = 200
print ( tableA[ "x" ].. "\n" ..tableA.y )
--另外表还可以如下形式(从1开始)
tableB = { "4" , "5" , "6" , "7" , "8" }
print ( tableB[ 1 ] )
 
--算术操作符
c 1 = 10 + 2
c 2 = 10 -2
c 3 = 10 * 2
c 4 = 10 / 2
c 5 = 10 ^ 2
c 6 = 10 % 2
c 7 = -10 + 2
print ( c 1. . "_" ..c 2. . "_" ..c 3. . "_" ..c 4. . "_" ..c 5. . "_" ..c 6. . "_" ..c 7 )
 
--控制操作
--if then elseif then else end
abc = 10
if  abc = = 10 then
     print ( "v1" )
elseif abc = = 9 then
     print ( "v2" )
else
     print ( "v3" )
end
 
--for
--从4(第一个参数)涨到10(第二个参数),每次增长以2(第三个参数)为单位
for i = 4 , 10 , 2 do
     print ( "for1:" ..i + 1 )
end
--也可以不制定最后一个参数,默认1的增长速度
for i = 4 , 10 do
     print ( "for2:" ..i + 1 )
end
 
tableFor = { "himi1" , "himi2" , "himi3" , "himi4" , "himi5" }
for k , v in pairs ( tableFor ) do
     print ( "for3:key:" ..k.. "value:" ..v )
end
 
--while
w 1 = 20
while true do
     w 1 = w 1 + 1
     if w 1 = = 25 then
         break
     end
end
print ( "whlile:" ..w 1 )
 
--repeat
     aa = 20
     repeat aa = aa + 2
         print ( "repeat:" ..aa )
     until aa > 28
 
--关系操作符
--需要注意的是不等于符号 ~=  而不是!=
ax = 10
bx = 20
 
if ax > bx then
     print ( "GX1" )
elseif ax < bx then
     print ( "GX2" )
elseif ax > = bx then
     print ( "GX3" )
elseif ax < = bx then
     print ( "GX4" )
elseif ax = = bx then
     print ( "GX5" )
elseif ax~ = bx then
     print ( "GX6" )
else
     print ( "GX7" )
end

 

其中主要需要注意的是判断语句不等于,不再是!= ,在Lua中是~= ,这个要注意。

源码下载地址: http://vdisk.weibo.com/s/wwgnO

 

另外关于一些常见的函数如下详解:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
--函数详解
 
--有一个返回值的函数
function funTestBackOne ( aCount )
     local aCount = aCount + 1
     return aCount
end
 
a = 20
print ( funTestBackOne ( a ) )
 
--有多个返回值的函数
function funTestBackMore ( )
     return 2 , 3
end
 
a , b = funTestBackMore ( )
print ( a.. " and " ..b )
 
--有变长参数的函数
function funTestUnKnow ( ... )
     print ( ... )
end
funTestUnKnow ( a , b , "Himi" )
 
--闭合函数(一个函数写在另外一个函数内)
function funTest 1 ( ... )
     local d = 12 ;
     d = d + ...
     function funTest 2 ( ... )
         print ( d )
     end
     funTest 2 ( )
end
 
funTest 1 ( 100 )

 

掌握这些Lua语言基础,基本足够你使用了。

转自:http://blog.csdn.net/xiaominghimi/article/details/8770395
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值