好记性不如铅笔头

C && C++, Lua, 编程

Lua快速学习笔记:语句

CONTENTS

备注:

1 本笔记只记录了LUA的一小部分内容,对于LUA的描述并不全面,以后随用随增加吧。
2 本笔记参考《Lua程序设计 第二版》,截图和代码属于原作者所有。
3 作者初学LUA,经验和能力有限,笔记可能有错误,还请各位路过的大牛们给予指点。

算术操作符:

Lua没有整数和浮点数的区别,因此关于取模运算符如下图:

关系操作符:

nil只与其自身相等。

逻辑操作符:

多重赋值语句:

v1,v2 = 10,20;
print("v1:" .. v1 .. "  v2:" .. v2); -->输出v1:10  v2:20
v1,v2 = v2,v1;
print("v1:" .. v1 .. "  v2:" .. v2); -->输出v1:20  v2:10

局部变量与语句块:

Local v = 10;
--显式界定一个语句块:
do
  local v = 100;
  print(v); -->输出100
end
print(v); -->>输出nil

if结构:

v1 = 0;

if v1 < 10 then
  print("v1 < 10");
end

if v1 < 10 then
  print("v1 < 10");
else
  print("v1 >= 10");
end

if v1 < 10 then
  print("v1 < 10");
elseif(v1 < 20) then
  print("v1 < 20");
else
  print("v1 >= 20");
end

while语句:

local num = 0;
while num < 4 do
  print(num);
  num = num + 1;
end

repeat..until类似于do..while:

local num = 5;
repeat
  print(num);
  num = num - 1;
until num == 0

数字型for语句:

不要在循环过程中修改控制变量的值!

泛型for语句:

这里先简单的笔记下最常用的:

tb = {"A","B","C",name="Hello",[10]="D",["age"] = 20};

for i,v in ipairs(tb) do
 print(i,v);
end

print("====");

for i,v in pairs(tb) do
 print(i,v);
end

输出:

1	A
2	B
3	C
====
1	A
2	B
3	C
10	D

关于pairs 和 ipairs:

Ipairs:【 http://manual.luaer.cn/pdf-ipairs.html 】

Returns three values: an iterator function, the table t, and 0, so that the construction
for i,v in ipairs(t) do body end
will iterate over the pairs (1,t[1]), (2,t[2]), ···, up to the first integer key absent from the table.

Pairs:【 http://manual.luaer.cn/pdf-pairs.html 】

Returns three values: the next function, the table t, and nil, so that the construction
 for k,v in pairs(t) do body end
will iterate over all key–value pairs of table t.

测试用Return语句:

发表评论

20 + 15 =

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据