Lua语言学习

类似于shell, 通过关键字确定区分,还好不是像py那样用空格 :)

没有标点符号

dofile调试

dofile(“lib1.lua”) – load your library

n = norm(3.4, 1.0)

print(twice(n)) –> 7.0880180586677

最好不要使用下划线加大写字母的标示符

字符串连接 ..

字符串转数字 tonumber()

1
2
print(tostring(10) == "10") --> true 
print(10 .. "" == "10") --> true

命令行运行lua

  1. 在运行以前,Lua 使用所有参数构造 arg 表。脚本名索引为 0,脚本的参数从 1 开始

增加。脚本前面的参数从-1 开始减少。

Lua 是动态类型语言,变量不要类型定义

[[ ]] 使用表示 R”

1
2
3
4
5
6
7
8
9
10
11
12
13
14
page = [[
<HTML>
<HEAD>
<TITLE>An HTML Page</TITLE>
</HEAD>

<BODY>
Lua
[[a text between double brackets]]
</BODY>
</HTML>
]]

io.write(page)

字符串连接 ..

字符串转数字 tonumber()

1
2
print(tostring(10) == "10") --> true 
print(10 .. "" == "10") --> true

列表

a = {[?]=?, [?]=?}

赋值

a, b = b, a

局部作用域

1
2
3
4
5
6
7
do
local a2 = 2*a
local d = sqrt(b^2 - 4*a*c)
x1 = (-b + d)/a2
x2 = (-b - d)/a2
end -- scope of 'a2' and 'd' ends here
print(x1, x2)

高频控制语句

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
if cond then
xxx
end;

if cond then
xxx
else
yyy
end;

if cond then
xxx
elseif cond2 then
yyy
else
zzz
end;

反向构造数据

1
2
3
4
5
6
   days = {"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"}
revDays = {}
for i,v in ipairs(days) do
revDays[v] = i
end

4.4 break return

误区

在控制结构的条件中除了 false 和 nil 为假,其他值都为真。所以 Lua 认为 0 和空串都是真

疑问

1
2
3
4
polyline = {color="blue", thickness=2, npoints=4, {x=0, y=0},
{x=-10, y=0}, {x=-10, y=1}, {x=0, y=1}
}
print(polyline[2].x) --> -10




请作者喝一杯咖啡☕️