Lua快速入门实例

注:以下例子选自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!

 

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

 

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

 

-- 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. --以数字开始,不合法

 

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

 

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

 

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

 

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

 

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

 

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,

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

 

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

 

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

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

 multiple line

with 'single'

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,b,c,d,e)

 

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

 

1       2       three   four    5

 

 

-- Example 10   -- More Assignments.

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

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

print(a,b)

a,b=b,a

print(a,b)

 

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

 

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中两点“..”表示字符串连接,对应其他语言中的“+”连接

 

a,b,c,d,e = 1, 1.123, 1E9, -123, .0008

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

 

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

 

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!")   -- 带括号,两者等价

 

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

 

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

 

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

 

360     2a

 

 

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

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

-- Simple if.

 

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# else if 不同

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

 

 

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

 

 

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

 

1       1

2       2

3       3

4       4

5       five

6       elephant

7       mouse

 

 

-- Example 25   -- break statement.

-- break is used to exit a loop. 

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

 

a=0

while true do

    a=a+1

    if a==10 then

        break

    end

end

 

print(a)

 

 

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

 

10

 

 

-- Example 26   -- Functions.

-- 最简单的函数调用

-- 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比较松,会直接忽略,即使你多写几个也没关系。]]

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

 

 

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

 

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

]]

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值