微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Lua快速入门实例

  2012-12-06 15:06:56

分类: Python/Ruby

注:以下例子选自LuaForWindows(LFW)组件QuickLuaTour,对其中做了一些主要的翻译并加上了个人的理解注释,没有安装过LFW的朋友可以一看,虽然例子很简单,但是对初学者快速入门会有所帮助。

 

关键词:LuaLua实例、QuickLuaTourLFWLua入门

 

-- Example 1   -- First Program.

-- Classic hello program.

print("hello")

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

Hello

-- Example 2   -- 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. ]]

-- And of course this example produces no

-- output,since it's all comments!

-- 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))

number

string

table

function

-- Example 4   -- Variable names. 变量命名

-- Variable names consist of letters,digits and underscores.

-- They cannot start with a digit.

-- 变量的名称由字母、数字、下划线组成,但是不能以数字开始

one_two_3 = 123 -- is valid varable name  --合法命名

-- 1_two_3 is not a valid variable name. --以数字开始,不合法

-- Example 5   -- More Variable names.

--[[ Lua中以下划线”_”开始的参数命名通常代表特殊的值,如(“_VERSION”),所以尽量不用使用以下划线开始命名。当时通常单个“_”代表虚假的参数。注:这是Lua一个语法,后面将讲到,如:local _,x = string.find(s,p)  ]]

-- 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.

-- Example 6   -- Case Sensitive.  大小写敏感

-- Lua is case sensitive so all variable names & keywords

-- must be in correct case.

-- Lua中所有的变量和关键字都是大小写敏感的

ab=1

Ab=2

AB=3

print(ab,Ab,AB)

1       2       3

-- Example 7   -- Keywords.   Lua关键字

--[[ Lua的关键字大家可以去参考“Lua Reference Manual”,附:5.1版本的参考手册在线地址:http://www.lua.org/manual/5.1/index.html   变量命名的时候应避免使用关键字,Lua是大小写敏感的,所以“and”是关键字,但“AND”不是是合法的命名,尽管如此,建议大家尽量不要用关键词(各种大小写版本)]]

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

-- Keywords cannot be used for variable names,208)"> -- 'and' is a keyword,but AND is not,so it is a legal variable name.

AND=3

print(AND)

3

-- Example 8   -- Strings.

--[[字符串可以用双引号(“”)也可以用单引号(‘’),类似于JavaScript语法,对于多行字符串,使用“[[ ]]”括起来 ]]

a="single 'quoted' string and double \"quoted\" string inside"

b='single \'quoted\' string and double "quoted" string inside'

c= [[ multiple line

with 'single'

and "double" quoted strings inside.]]

print(a)

print(b)

print(c)

single 'quoted' string and double "quoted" string inside

 multiple line

and "double" quoted strings inside.

-- Example 9   -- Assignments.  赋值

--[[可以一次对多个变量赋值,规则:如果等号(“=”)右边多了,则舍弃,左边多了,则赋值为空(nil ]]

-- Multiple assignments are valid. 

--  var1,var2=var3,var4

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

print(a,e)

1       2       three   four    5

-- Example 10   -- More Assignments.

-- Multiple assignments allows one line to swap two variables.

-- 表达式 a,b=b,a表示ab的值交换

ottom:0px; line-height:25px; color:rgb(51,b)

ottom:0px; line-height:25px; color:rgb(51,a

1       2

2       1

-- Example 11   -- Numbers.

-- Multiple assignment showing different number formats.

-- Two dots (..) are used to concatenate strings (or a

-- string and a number). – Lua中两点“..”表示字符串连接,对应其他语言中的“+”连接

ottom:0px; line-height:25px; color:rgb(51,1.123,1E9,-123,.0008

print("a="..a,"b="..b,"c="..c,"d="..d,"e="..e)

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

-- Example 12   -- More Output.

-- More writing output.  –多种输出方式或写法

print "Hello from Lua!"    -- 不带括号

print("Hello from Lua!")   -- 带括号,两者等价

Hello from Lua!

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

-- Example 14   -- Tables.

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

-- Simple table creation.

a={} -- {} creates an empty table

b={1,3} -- creates a table containing numbers 1,3

c={"a","b","c"} -- creates a table containing strings a,c

ottom:0px; line-height:25px; color:rgb(51,c) -- tables don't print directly,we'll get back to this!!

table: 00410A58 table: 00410E90 table: 00410FB8

-- Example 15   -- More Tables.

-- 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"])

360     2a

-- Example 16   -- if statement.  if语句

-- Lua中的语句块语法有点类似VB都是以end结束

-- Simple if.

if a==1 then

    print ("a is one")

end

a is one

-- Example 17   -- if else statement.

b="happy"

if b=="sad" then

    print("b is sad")

else

    print("b is not sad")

b is not sad

-- Example 18   -- if elseif else statement

-- 需要注意的是“elseif 是连在一起的,这个和C# else if 不同

c=3

if c==1 then

    print("c is 1")

elseif c==2 then

    print("c is 2")

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

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

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

-- is equivalent to

    b = "one"

    b = "not one"

one

-- Example 20   -- while statement.

-- while语句

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

    a=a+1

    io.write(a.." ")

2 3 4 5

-- Example 21   -- repeat until statement.

a=0

repeat

    print(a)

until a==5

1

2

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.

ottom:0px; line-height:25px; color:rgb(51,6,3 do io.write(a) end

1234

14

-- Example 23   -- More for statement.

-- for语句的Generic for变体

-- Sequential iteration form.

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

1       1

2       2

3       3

4       4

-- Example 24   -- Printing tables.

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

-- Simple way to print tables.

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

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

5       five

6       elephant

7       mouse

-- Example 25   -- break statement.

-- break is used to exit a loop. 

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

while true do

    if a==10 then

        break

    end

10

-- Example 26   -- Functions.

-- 最简单的函数调用

-- Define a function without parameters or return value.

function myFirstLuaFunction()

    print("My first lua function was called")

-- Call myFirstLuaFunction.

myFirstLuaFunction()

My first lua function was called

-- Example 27   -- More functions.

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

-- Define a function with a return value.

function mySecondLuaFunction()

    return "string from my second function"

-- Call function returning a value.

a=mySecondLuaFunction("string")

string from my second function

-- Example 28   -- More functions.

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

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

function myFirstLuaFunctionWithMultipleReturnValues(a,c)

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

ottom:0px; line-height:25px; color:rgb(51,e,f = myFirstLuaFunctionWithMultipleReturnValues(1,"three")

ottom:0px; line-height:25px; color:rgb(51,f)

1       2       three   My first lua function with multiple return values

1                        true

-- 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,208)"> myfunc()

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,...))

printf("Hello %s from %s on %s\n",208)">        os.getenv"USER" or "there",_VERSION,os.date())

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,208)">   logging,unittests,GUI toolkits,web frameworks,and many more.

]]

-- 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,208)"> -- math.ceil,math.cos,math.cosh,math.deg,math.exp,math.floor,208)"> -- math.fmod,math.frexp,math.huge,math.ldexp,math.log,math.log10,208)"> -- math.max,math.min,math.modf,math.pi,math.pow,math.rad,208)"> -- math.random,math.randomseed,math.sin,math.sinh,math.sqrt,208)"> -- math.tan,math.tanh

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

 

3           3.1415926535898

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

-- String functions:

-- string.byte,string.char,string.dump,string.find,string.format,208)"> -- string.gfind,string.gsub,string.len,string.lower,string.match,208)"> -- string.rep,string.reverse,string.sub,string.upper

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

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);

ottom:0px; line-height:25px; color:rgb(51,4);

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

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,208)"> -- io.read,io.stderr,io.stdin,io.stdout,io.tmpfile,io.type,io.write,208)"> -- file:close,file:flush,file:lines,file:read,208)"> -- file:seek,file:setvbuf,file:write

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

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,208)"> -- os.remove,os.rename,os.setlocale,os.time,os.tmpname

print(os.date())

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",208)">     value="Quit this multiline edit app to continue Tutorial!",208)">     border="YES"

    }

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

dlg:show()

print("Exit GUI app to continue!")

iup.MainLoop()

-- 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

]]

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐