最简明Lua教程 The simplest Lua tutorial

1. 第一个程序
-- Example 1   -- First Program.
-- Classic hello program.

print("hello")

-------- Output ------
hello
2. 注释
-- 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 ------
3. 变量
-- 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
4. 变量命名
-- 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 ------
5. 更多变量命名
-- 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
6. 大小写
-- Example 6   -- Case Sensitive.
-- Lua is case sensitive so all variable names & keywords
-- must be in correct case.

ab=1
Ab=2
AB=3
print(ab,Ab,AB)

-------- Output ------
1       2       3
7. 关键字(保留字)
-- 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
8. 字符串
-- Example 8   -- Strings.

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.
9. 赋值
-- Example 9   -- Assignments.
-- 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
10. 更多赋值
-- Example 10   -- More Assignments.
-- Multiple assignments allows one line to swap two variables.

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

-------- Output ------
1       2
2       1
11. 数值
-- Example 11   -- Numbers.
-- Multiple assignment showing different number formats.
-- Two dots (..) are used to concatenate strings (or a
-- string and a number).

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
12. 输出
-- Example 12   -- More Output.
-- More writing output.

print "Hello from Lua!"
print("Hello from Lua!")

-------- Output ------
Hello from Lua!
Hello from Lua!
13. 更多输出
-- Example 13   -- More Output.
-- io.write writes to stdout but without new line.

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

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

-------- Output ------
Hello from Lua!Hello from Lua!
14. 表
-- Example 14   -- Tables.
-- 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: 00F064A0 table: 00F06590 table: 00F064C8
15. 更多表
-- Example 15   -- More Tables.
-- 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
16. if 语句
-- Example 16   -- if statement.
-- Simple if.

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

-------- Output ------
a is one
17. if - else 语句
-- 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
18. if - elseif - else 语句
-- Example 18   -- if elseif else statement

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
19. 条件赋值
-- Example 19   -- Conditional assignment.
-- value = test and x or 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
20. while 循环语句
-- Example 20   -- while statement.

a=1
while a~=5 do -- Lua uses ~= to mean not equal
    a=a+1
    io.write(a.." ")
end

-------- Output ------
2 3 4 5
21. repeat - until 循环
-- Example 21   -- repeat until statement.

a=0
repeat
    a=a+1
    print(a)
until a==5

-------- Output ------
1
2
3
4
5
22. for 循环
-- Example 22   -- for statement.
-- 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
23. 更多 for 循环
-- Example 23   -- More for statement.
-- 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
24. 打印表
-- Example 24   -- Printing tables.
-- 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
25. break 语句
-- Example 25   -- break statement.
-- break is used to exit a loop.

a=0
while true do
    a=a+1
    if a==10 then
        break
    end
end

print(a)

-------- Output ------
10
26. 函数
-- 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
27. 更多函数
-- Example 27   -- More functions.

-- 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
28. 更多函数
-- Example 28   -- More functions.

-- 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
29. 变量作用域
-- Example 29   -- Variable scoping and functions.
-- 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
30. 格式化打印
-- Example 30   -- Formatted printing.
-- 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 09/19/24 16:38:29
31. 标准库
-- 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 ------
32. math 库
-- Example 32   -- Standard Libraries - math.

-- 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
33. string 库
-- Example 33   -- Standard Libraries - string.

-- 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
34. table 库
-- Example 34   -- Standard Libraries - 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
35. 输入输出库
-- Example 35   -- Standard Libraries - input/output.

-- 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
36. 操作系统库
-- 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 ------
09/19/24 16:39:01
37. 外部库
-- 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 ------
failed to load & run sample code
error loading module 'iuplua' from file 'D:\Work\lua-5.1\clibs\iuplua51.dll':
        The specified module could not be found.
38. 更多

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

lua中文教程,原名:programming in lua 目录 版权声明..............i 译序..i 目录iii 第一篇语言.......1 第0章序言.......1 0.1 序言..........1 0.2 Lua的使用者................2 0.3 Lua的相关资源............3 0.4 本书的体例.................3 0.5 关于本书...3 0.6 感谢..........4 第1章起点.......5 1.1 Chunks.......5 1.2 全局变量...7 1.3 词法约定...7 1.4 命令行方式.................7 第2章类型和值9 2.1 Nil..............9 2.2 Booleans....9 2.3 Numbers...10 2.4 Strings......10 2.5 Functions.12 2.6 Userdata and Threads.12 第3章表达式..13 3.1 算术运算符...............13 3.2 关系运算符...............13 3.3 逻辑运算符...............13 3.4 连接运算符...............14 3.5 优先级.....15 3.6表的构造..15 第4章基本语法................18 4.1 赋值语句.18 4.2 局部变量与代码块(block)......19 4.3 控制结构语句...........20 Programming in Lua iv Copyright ® 2005, Translation Team, www.luachina.net 4.4 break和return语句......23 第5章函数......24 5.1 返回多个结果值.......25 5.2可变参数..27 5.3 命名参数.28 第6章再论函数................30 6.1 闭包........32 6.2 非全局函数...............34 6.3 正确的尾调用(Proper Tail Calls)...36 第7章迭代器与泛型for....40 7.1 迭代器与闭包...........40 7.2 范性for的语义...........42 7.3 无状态的迭代器.......43 7.4 多状态的迭代器.......44 7.5 真正的迭代器...........45 第8章编译·运行·调试47 8.1 require函数.................49 8.2 C Packages.................50 8.3 错误........51 8.4 异常和错误处理.......52 8.5 错误信息和回跟踪(Tracebacks)....53 第9章协同程序................56 9.1 协同的基础...............56 9.2 管道和过滤器...........58 9.3 用作迭代器的协同...61 9.4 非抢占式多线程.......63 第10章完整示例..............68 10.1 Lua作为数据描述语言使用........68 10.2 马尔可夫链算法.....71 第二篇 tables与objects........75 第11章数据结构..............76 11.1 数组......76 11.2 阵和多维数组.........77 11.3 链表......78 11.4 队列和双端队列.....78 11.5 集合和包.................80 11.6 字符串缓冲.............80 第12章数据文件与持久化..................84 12.1 序列化...86 Programming in Lua v Copyright ® 2005, Translation Team, www.luachina.net 第13章 Metatables and Metamethods...92 13.1 算术运算的Metamethods............92 13.2 关系运算的Metamethods............95 13.3 库定义的Metamethods................96 13.4 表相关的Metamethods................97 第14章环境..103 14.1 使用动态名字访问全局变量...103 14.2声明全局变量........104 14.3 非全局的环境.......106 第15章 Packages.............109 15.1 基本方法...............109 15.2 私有成员(Privacy)................111 15.3 包与文件................112 15.4 使用全局表............113 15.5 其他一些技巧(Other Facilities)...115 第16章面向对象程序设计.................118 16.1 类.........119 16.2 继承.....121 16.3 多重继承...............122 16.4 私有性(privacy)...................125 16.5 Single-Method的对象实现方法127 第17章 Weak表...............128 17.1 记忆函数...............130 17.2 关联对象属性.......131 17.3 重述带有默认值的表...............132 第三篇标准库134 第18章数学库................135 第19章 Table库...............136 19.1数组大小................136 19.2 插入/删除..............137 19.3 排序.....137 第20章 String库..............140 20.1 模式匹配函数.......141 20.2 模式.....143 20.3 捕获(Captures).146 20.4 转换的技巧(Tricks of the Trade)151 第21章 IO库..157 21.1 简单I/O模式..........157 21.2 完全I/O 模式........160 Programming in Lua vi Copyright ® 2005, Translation Team, www.luachina.net 第22章操作系统库........165 22.1 Date和Time............165 22.2 其它的系统调用...167 第23章 Debug库..............169 23.1 自省(Introspective)..............169 23.2 Hooks...173 23.3 Profiles.174 第四篇 C API..177 第24章 C API纵览..........178 24.1 第一个示例程序...179 24.2 堆栈.....181 24.3 C API的错误处理..186 第25章扩展你的程序....188 25.1 表操作.189 25.2 调用Lua函数.........193 25.3 通用的函数调用...195 第26章调用C函数..........198 26.1 C 函数..198 26.2 C 函数库................200 第27章撰写C函数的技巧..................203 27.1 数组操作...............203 27.2 字符串处理...........204 27.3 在C函数中保存状态.................207 第28章 User-Defined Types in C........212 28.1 Userdata.................212 28.2 Metatables..............215 28.3 访问面向对象的数据...............217 28.4 访问数组...............219 28.5 Light Userdata........220 第29章资源管理............222 29.1 目录迭代器...........222 29.2 XML解析...............225
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

皓月如我

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值