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