代码改变世界

Lua快速入门

2014-04-17 15:34  youxin  阅读(901)  评论(0编辑  收藏  举报

QuickLuaTour教程:(来自LuaForWindows的quickLuaTour)

Lua变量类型:

Lua 是一种 动态类型语言。 这意味着变量没有类型,只有值才有类型。 语言中不存在类型定义。而所有的值本身携带它们自己的类型信息。

(变量无类型,对象有类型)

有8种基本类型:nil、布尔值(boolean)、数字体(number)、字符串型(string)、用户自定义类型(userdata)、函数(function)、线程(thread)和表(table)。

 

-- Example 1   -- First Program.

-- Classic hello program.

 

print("hello")

 

-------- Output ------

 

Hello

Example2:Comments.  注释

--单行注释以双连字符--开头多行注释—[[以开始,以]]结束

-- Single line comments in Lua start with double hyphen.  

--[[ Multiple line comments start                 

with double hyphen and two square brackets.

  and end with two square brackets. ]]

 

 


-- Example 3 -- Variables.
-- Variables hold values which have types, variables don't have types.

 

a=1
b="abc"
c={}
d=print

 

print(type(a))
print(type(b))
print(type(c))
print(type(d))

 


-------- Output ------

 

number
string
table
function

 

Press 'Enter' key for next example

 

 

-- Example 4 -- Variable names.
-- Variable names consist of letters, digits and underscores.
-- They cannot start with a digit.


-- Example 5 -- More Variable names.
-- The underscore is typically used to start special values
-- like _VERSION in Lua.

print(_VERSION)

-- So don't use variables that start with _,
-- but a single underscore _ is often used as a
-- dummy variable.

 

-------- Output ------

Lua 5.1


-- Example 6 -- Case Sensitive.
-- Lua is case sensitive so all variable names & keywords
-- must be in correct case.


-- Example 7 -- Keywords.
-- Lua reserved words are: and, break, do, else, elseif,
-- end, false, for, function, if, in, local, nil, not, or,
-- repeat, return, then, true, until, while.

-- Keywords cannot be used for variable names,
-- 'and' is a keyword, but AND is not, so it is a legal variable name.
AND=3
print(AND)

 

-------- Output ------

3


-- Example 9 -- Assignments.
-- Multiple assignments are valid. 多个赋值是有效的。,规则:如果等号(“=”)右边多了,则舍弃,左边多了,则赋值为空(nil ]]
-- var1,var2=var3,var4

a,b,c,d,e = 1, 2, "three", "four", 5

print(a,b,c,d,e)

 

-------- Output ------

1 2 three four 5


-- Example 10 -- More Assignments.
-- Multiple assignments allows one line to swap two variables.(同python)

print(a,b)
a,b=b,a
print(a,b)

-- Example 11 -- Numbers.
-- Multiple assignment showing different number formats.
-- Two dots (..) are used to concatenate strings (or a
-- string and a number). 2个点号连接string或string和number。

a,b,c,d,e = 1, 1.123, 1E9, -123, .0008
print("a="..a, "b="..b, "c="..c, "d="..d, "e="..e)

 


-- Example 12 -- More Output.
-- More writing output.

print "Hello from Lua!"
print("Hello from Lua!") 不带括号和带括号均可以。

 

-------- Output ------

Hello from Lua!
Hello from Lua!

-------- Output ------

a=1 b=1.123 c=1000000000 d=-123 e=0.0008

--[[什么时候可以省略括号?  这是以种特殊的情况,只有当函数的参数只有一个,而且这个参数是字面上的字符串串a literal string:即直接传字符串,而不是值为字符串的参数变量)或者蚕食是table结构。这两种情况才可以省略圆括号]]


-- Example 13 -- More Output.
-- io.write writes to stdout but without new line. io.write()不换行.

io.write("Hello from Lua!")
io.write("Hello from Lua!")

-- Use an empty print to write a single new line.
print()

 


-- Example 14 -- Tables.
-- Simple table creation. 表结构在Lua中特别常见,可以存储任何类型,很灵活。非常类似于JS中的一个对象。

a={} -- {} creates an empty table
b={1,2,3} -- creates a table containing numbers 1,2,3
c={"a","b","c"} -- creates a table containing strings a,b,c
print(a,b,c) -- tables don't print directly, we'll get back to this!!


-------- Output ------

table: 008AC918 table: 008ACA30 table: 008ACAA8

 


-- Example 15 -- More Tables.
-- Associate index style.

-- Lua中表结构和JS中的对象一样可以随时增加或删除(直接赋值nil)属性。

--[[ 读取有多种方式,可以用点“.”的方式,也可以用索引index,不过在Lua有点特殊,首先索引是从一开始,其次index=1并不一定是第一个元素值,比如下面的address[1]=nil,而不是“Wyman Street,具体的以后在讲]]

-- Associate index style.

address={} -- empty address
address.Street="Wyman Street"
address.StreetNumber=360
address.AptNumber="2a"
address.City="Watertown"
address.State="Vermont"
address.Country="USA"

print(address.StreetNumber, address["AptNumber"])

 

-------- Output ------

360 2a


-- Example 16 -- if statement.
-- Simple if.a中的语句块语法有点类似VB都是以end结束

a=1
if a==1 then
print ("a is one")
end


-------- Output ------

a is one


-- Example 17 -- if else statement.

b="happy"
if b=="sad" then
print("b is sad")
else
print("b is not sad")
end


-------- Output ------

b is not sad

 


-- Example 18 -- if elseif else statement elseif连在一起

c=3

if c==1 then

    print("c is 1")

elseif c==2 then

    print("c is 2")

else

    print("c isn't 1 or 2, c is "..tostring(c))

end

 

-------- Output ------

c isn't 1 or 2, c is 3

 

-- Example 19   -- Conditional assignment. 条件语句

 

-- value = test and x or y

 

--注:value = test and x or y 等价于我们平时写的三元运算符(“?:)的效果 value= test?x:y

 

a=1

 

b= (a==1) and "one" or "not one"

 

print(b)

 

-- is equivalent to

 

a=1

 

if a==1 then

 

    b = "one"

 

else

 

    b = "not one"

 

end

 

print(b)

 

 

 

-------- Output ------

 

one

 

one

 

-- Example 20   -- while statement.

 

-- while语句

 

a=1

 

while a~=5 do    -- Lua uses ~= to mean not equal

 

    a=a+1

 

    io.write(a.." ")

 

end

 

-------- Output ------

 

2 3 4 5

 

 

-- Example 21   -- repeat until statement.

 

 

 

a=0

 

repeat

 

    a=a+1

 

    print(a)

 

until a==5  --until为真时停止。do-while是为真时继续。

 

 

 

-------- Output ------

 

1 2 3 4 5 

 

 

-- Example 22   -- for statement.

 

-- for语句有两种变体,一种叫 Numeric for ,一种叫 Generic for 就是例23中的for…in结构

 

--[[ Numeric for 的语法为:

 

for var=exp1,exp2,exp3 do something end

 

  等价于C#中的:for(int i=exp1; i<=exp2; i+=exp3) { something }

 

  ]]

 

-- Numeric iteration form.

 

 

 

-- Count from 1 to 4 by 1.

 

for a=1,4 do

  io.write(a)

end

 

 

 

print()

 

 

 

-- Count from 1 to 6 by 3.

 

for a=1,6,3 do io.write(a) end

 

-------- Output ------

 

 

 

1234

 

14

 

-- Example 23   -- More for statement.

 

-- for语句的Generic for变体

 

-- Sequential iteration form.

 

for key,value in pairs({1,2,3,4}) do print(key, value) end

 

-------- Output ------

1 1
2 2
3 3
4 4

 

 

-- Example 24   -- Printing tables.

 

-- 用简单的方式遍历table结构,并输出

 

-- Simple way to print tables.

 

a={1,2,3,4,"five","elephant", "mouse"}

 

 

 

for i,v in pairs(a) do print(i,v) end

 

 

-- Example 25   -- break statement.

 

-- break is used to exit a loop. 

 

-- break关键字用于跳出循环,当然return也可以,不过有区别

 

 

-- Example 26   -- Functions.

-- 最简单的函数调用 (function也要有end

-- Define a function without parameters or return value.

function myFirstLuaFunction()

    print("My first lua function was called")

end

 

-- Call myFirstLuaFunction.

myFirstLuaFunction()

 

-------- Output ------

My first lua function was called

 

 

-- Example 27   -- More functions.

 

--[[ 带返回值的函数调用,大家注意a=mySecondLuaFunction("string")带了一个参数,但是mySecondLuaFunction定义并没有带参数,这个在Lua比较松,会直接忽略,即使你多写几个也没关系。]] (同js)

 

-- Define a function with a return value.

 

function mySecondLuaFunction()

 

    return "string from my second function"

 

end

 

-- Call function returning a value.

 

a=mySecondLuaFunction("string")

 

print(a)

 

-------- Output ------

 

 

 

string from my second function

 

 

- Example 28   -- More functions.

 

--[[ 使用函数返回值对多个变量赋值,规则和多参数赋值一样,如果函数返回值多了,则抛弃,少了则少的赋值为nil  ]]

 

-- Define function with multiple parameters and multiple return values.

 

function myFirstLuaFunctionWithMultipleReturnValues(a,b,c)

 

    return a,b,c,"My first lua function with multiple return values", 1, true

 

end

 

 

 

a,b,c,d,e,f = myFirstLuaFunctionWithMultipleReturnValues(1,2,"three")

 

print(a,b,c,d,e,f)

如果多一个变量会输出nil。

 

 

-- Example 29   -- Variable scoping and functions. 变量作用域

 

--[[ Lua中,默认声明的变量为全局变量,local 为修饰符的为局部变量,局部变量只在所属的语句块内有效]]

 

-- All variables are global in scope by default.

 

 

 

b="global"

 

-- To make local variables you must put the keyword 'local' in front.

 

function myfunc()

 

    local b=" local variable"

 

    a="global variable"

 

    print(a,b)

 

end

 

 

 

myfunc()

 

print(a,b)

 

------- Output ------

 

global variable  local variable

 

global variable global

 

 

-- Example 30   -- Formatted printing.  字符串格式

--[[ 字符串格式大家可以去参考Lua参考手册“Lua Reference Manualhttp://www.lua.org/manual/5.1/index.html 这里重点说明一下在这些例子中第一次见到三个点“”的作用,在Lua中在函数的参数列表中,表示参数的格式是可变不固定的,当这个函数在被调用时,函数的所有参数都被存储在一个名为arg的表结构中,同时arg还有一个n属性,代表实际传人的可变参数的个数,那么可以通过arg来访问所有的可变参数了,细节的以后再讲]]

-- An implementation of printf.

 

function printf(fmt, ...)

    io.write(string.format(fmt, ...))

end

printf("Hello %s from %s on %s\n",

       os.getenv"USER" or "there", _VERSION, os.date())

-------- Output ------

Hello there from Lua 5.1 on 08/11/11 16:48:19

 

 

-- Example 31   --[[

 

 Standard Libraries

 

  Lua has standard built-in libraries for common operations in

 

  math, string, table, input/output & operating system facilities.

 

 

 

 External Libraries

 

  Numerous other libraries have been created: sockets, XML, profiling,

 

  logging, unittests, GUI toolkits, web frameworks, and many more.

 

 

 

]]

 

 

 

-------- Output ------

 

 

 

-- Example 32   -- Standard Libraries - math.  Lua中标准的数学函数

 

--[[详细请参考Lua参考手册“Lua Reference Manual http://www.lua.org/manual/5.1/index.html  ]]

 

-- Math functions:

 

-- math.abs, math.acos, math.asin, math.atan, math.atan2,

 

-- math.ceil, math.cos, math.cosh, math.deg, math.exp, math.floor,

 

-- math.fmod, math.frexp, math.huge, math.ldexp, math.log, math.log10,

 

-- math.max, math.min, math.modf, math.pi, math.pow, math.rad,

 

-- math.random, math.randomseed, math.sin, math.sinh, math.sqrt,

 

-- math.tan, math.tanh

 

 

 

print(math.sqrt(9), math.pi)

 

 

 

 

 

-------- Output ------

 

 

 

3           3.1415926535898

 

 

 

 

 

-- Example 33   -- Standard Libraries - string.  Luastring类库

 

 

 

-- String functions:

 

-- string.byte, string.char, string.dump, string.find, string.format,

 

-- string.gfind, string.gsub, string.len, string.lower, string.match,

 

-- string.rep, string.reverse, string.sub, string.upper

 

 

 

print(string.upper("lower"),string.rep("a",5),string.find("abcde", "cd"))

 

 

 

-------- Output ------

 

 

 

LOWER   aaaaa   3       4

 

 

 

 

 

-- Example 34   -- Standard Libraries - table.  Lua中的table类库

 

 

 

-- Table functions:

 

-- table.concat, table.insert, table.maxn, table.remove, table.sort

 

 

 

a={2}

 

table.insert(a,3);

 

table.insert(a,4);

 

table.sort(a,function(v1,v2) return v1 > v2 end)

 

for i,v in ipairs(a) do print(i,v) end

 

 

 

-------- Output ------

 

1       4

2       3

 

3       2

 

 

 

-- Example 35   -- Standard Libraries - input/output.  输入输出

 

--[[其中:io.write函数和print函数的功能相同都是输出显示,只是io.write输出后不换行]]

 

-- IO functions:

 

-- io.close , io.flush, io.input, io.lines, io.open, io.output, io.popen,

 

-- io.read, io.stderr, io.stdin, io.stdout, io.tmpfile, io.type, io.write,

 

-- file:close, file:flush, file:lines ,file:read,

 

-- file:seek, file:setvbuf, file:write

 

 

 

       print(io.open("file doesn't exist", "r"))

 

-------- Output ------

 

 

 

nil     file doesn't exist: No such file or directory   2

 

 

 

 

 

-- Example 36   -- Standard Libraries - operating system facilities. 操作系统中类库

 

 

 

-- OS functions:

 

-- os.clock, os.date, os.difftime, os.execute, os.exit, os.getenv,

 

-- os.remove, os.rename, os.setlocale, os.time, os.tmpname

 

 

 

print(os.date())

 

 

 

 

 

-------- Output ------

 

 

 

08/11/11 17:07:30

 

 

 

 

 

-- Example 37   -- External Libraries. 扩展类库

 

-- Lua has support for external modules using the 'require' function

 

-- INFO: A dialog will popup but it could get hidden behind the console.

 

 

 

require( "iuplua" )

 

ml = iup.multiline

 

    {

 

    expand="YES",

 

    value="Quit this multiline edit app to continue Tutorial!",

 

    border="YES"

 

    }

 

dlg = iup.dialog{ml; title="IupMultiline", size="QUARTERxQUARTER",}

 

dlg:show()

 

print("Exit GUI app to continue!")

 

iup.MainLoop()

 

-------- Output ------

 

-- Example 38   --[[

 

--  后续学习lua-users wiki

 

 To learn more about Lua scripting see

 

 

 

 Lua Tutorials: http://lua-users.org/wiki/TutorialDirectory

 

 

 

 "Programming in Lua" Book: http://www.inf.puc-rio.br/~roberto/pil2/

 

 

 

 Lua 5.1 Reference Manual:

 

     Start/Programs/Lua/Documentation/Lua 5.1 Reference Manual

 

 

 

 Examples: Start/Programs/Lua/Examples

 

]]

 

-------- Output ------

 

 

 

 

 参考:http://xuzhihong1987.blog.163.com/blog/static/26731587201171152614685/