chapter 3Expressions

math.floor 功 能: 返回小于或者等于指定表达式的最大整数 .

The following rule defines the modulo operator:
a % b == a - math.floor(a/b)*b  ,取模竟然可以这样表达出来

--突然的今天我知道为什么了, a=a%b +math.floor(a/b)*b.    如果是c/c++ java里面两个整数除的话,余数会丢弃的,

(a/b)*b,其实就是b的整数倍的结果,余数丢掉,a-(a/b)*b 不就是丢掉的余数了吗,,,2013-12-04


For integer operands, it has the usual meaning, with the result always having  the same sign as the second argument.

(整数模运算就是常熟悉的运算,a%b, a里面有多少个b,不完整的就不要了,符号决定在第二个数)

For real operands, it has some extra   uses., 小数取模运算有些特殊的用法:

For instance, x%1 is the fractional part of x, and so x-x%1 is its integer   part.

Similarly, x-x%0.01 is x with exactly two decimal digits:
x = math.pi
print(x - x%0.01) --> 3.14


c=25.26524
b=10;
d=c-math.floor(c/b)*b;
print(c-c%0.01); --〉25.26, 虽然取了两位小数,但其实是没有四舍五入的,只是按位取了,,,不过这种算法还是很有用的。。。


+=   -= ,这些运算符号不存在


The == operator tests for equality; the ~= operator is the negation of equality. ,注意不是!=

Specifically, nil is equal only to itself.

Lua compares tables and userdata by reference, that is, two such values are
considered equal only if they are the very same object. For instance, after the
code
a = {}; a.x = 1; a.y = 0
b = {}; b.x = 1; b.y = 0
c = a
you have a==c but a~=b. --也就是只是比较地址,内容就不管了

Lua   compares strings in alphabetical order, which follows the locale set for Lua.

print("a"<"b"); --true

When comparing values with different types, you must be careful: remember
that "0" is different from 0. Moreover, 2<15 is obviously true, but "2"<"15"
is false (alphabetical order). To avoid inconsistent results, Lua raises an error
when you mix strings and numbers in an order comparison, such as 2<"15".



3.3 Logical Operators

The logical operators are and, or, and not. Like control structures, all logical
operators consider both the boolean false and nil as false, and anything else
as true.
The and operator returns its first argument if it is false; otherwise, it
returns its second argument. The or operator returns its first argument if it is
not false; otherwise, it returns its second argument: 好纠结,,,

其实也很好理解,关键是我们要知道他们是short-cut evaluation 的, and ,如果第一都是false,那么就不要再看第二个了,直接返回第一个就是了,如果是true,那么结果就取决第二个,第二个是真,那就是真的,假就是假,

or 也是同样的道理,第一个都是真了,直接返回第一个就是了
print(4 and 5) --> 5
print(nil and 13) --> nil
print(false and 13) --> false
print(4 or 5) --> 4
print(false or 5) --> 5

Both and and or use short-cut evaluation, that is, they evaluate their second
operand only when necessary. Short-cut evaluation ensures that expressions
like (type(v)=="table"and v.tag=="h1") do not cause run-time errors: Lua
will not try to evaluate v.tag when v is not a table.
A useful Lua idiom is x=x or v, which is equivalent to
if not x then x = v end
That is, it sets x to a default value v when x is not set (provided that x is not set
to false).


Another useful idiom is (a and b)or c, or simply a and b or c, because and
has a higher precedence than or. (相当于三目运算符号)

For instance, we can select the maximum of two  numbers x and y with a statement like
max = (x > y) and x or y


The not operator always returns a boolean value:
print(not nil) --> true
print(not false) --> true
print(not 0) --> false
print(not not 1) --> true
print(not not nil) --> false


3.4 Concatenation


Lua denotes the string concatenation operator by .. (two dots). If any operand
is a number, Lua converts this number to a string.


print("Hello " .. "World") --> Hello World
print(0 .. 1) --> 01
print(000 .. 01) --> 01
Remember that strings in Lua are immutable values. The concatenation operator
always creates a new string, without any modification to its operands:

a = "Hello"
print(a .. " World") --> Hello World
print(a) --> Hello


also remember ,can not concate with boolean and nil data type




3.5 The Length Operator

The length operator works on strings and tables. On strings, it gives the number
of bytes in the string.

On tables, it gives the length of the sequence represented  by the table. (注意是sequence of the table,而不是总的元素个数)

mytable={

"this is the first sequence",

"trevor"="this is not in the sequence";

sun="this is also not in the sequence",

nil,

"this is the third sequence"

};

mytable[2]="this is the second sequence"; //其实是因为这里把nil ,这个hole 填了

print(#mytable);-->3, nil, 其实不在table 里面

As we saw in the last chapter, the length operator isunpredictablefor lists
with holes (nils). It only works for sequences, which we defined as lists without
holes. More precisely, a sequence is a table where the numeric keys comprise a
set 1; : : : ; n for some n. (Remember that any key with value nil is actually not in
the table.) In particular, a table with no numeric keys is a sequence with length
zero.



b = {}
b[1] = 1
b[2] = nil -- does nothing, as a[2] is already nil
b[3] = 1
b[4] = 1
print("b sequence" .. #b); -- here print 4.



b = {
1,
abc="what the whole";
nil,
3,
4,
nil
}

print("b sequence" .. #b); --here print 1. why????


a = {}
a[1] = 1
a[10000] = 1
Should we consider a as a list with 10000 elements, where 9998 of them are nil?
Now, the program does this:

a[10000] = nil
What is the list length now? Should it be 9999, because the program deleted
the last element? Or maybe still 10000, as the program only changed the last
element to nil? Or should the length collapse to 1?



a = {10, 20, 30, nil, nil}

pint(#a);-->3

a = {10, 20, 30, nil, nil,7}

print(#a);-->6,,,,确实有个洞真麻烦,,,


b = {
1,
3,
4,
nil,
nil,
5,
6,
nil
}

print("b sequence" .. #b);--〉竟然是3,

这样总结把: 中间有洞,最后也有洞的,,#table,只会返回第一个洞之前的元素sequence.

如果中间有洞,最后没洞,当没洞处理。

如果只是最后有洞,把最后的去到后的sequence.

不知道这样是否全面,但从当前版本来看,,试验结果如此,with Lua5.2


3.6 Precedence
Operator precedence in Lua follows the table below, from the higher to the lower
priority:
^
not # - (unary)
* / %
+ -
..
< > <= >= ~= ==
and
or
All binary operators are left associative, except for ‘^’ (exponentiation) and ‘..’
(concatenation), which are right associative. Therefore, the following expressions
on the left are equivalent to those on the right:
a+i < b/2+1 <--> (a+i) < ((b/2)+1)
5+x^2*8 <--> 5+((x^2)*8)
a < y and y <= z <--> (a < y) and (y <= z)
-x^2 <--> -(x^2)
x^y^z <--> x^(y^z)


3.7 Table Constructors

days = {"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"}
will initialize days[1] with the string “Sunday” (the first element of the constructor  has index 1, not 0)
print(days[4]) --> Wednesday
Lua also offers a special syntax to initialize a table record-like, as in the next
example:
a = {x=10, y=20}
This previous line is equivalent to these commands:
a = {}; a.x=10; a.y=20


The original expression, however, is faster, because Lua creates the table already
with the right size.


w = {x=0, y=0, label="console"}
x = {math.sin(0), math.sin(1), math.sin(2)}
w[1] = "another field" -- add key 1 to table 'w'
x.f = w -- add key "f" to table 'x'
print(w["x"]) --> 0
print(w[1]) --> another field
print(x.f[1]) --> another field,Notice, 先解析x.f,然后才到[1]
w.x = nil -- remove field "x"


//一次性构造更爽又快

polyline = {color="blue",
thickness=2,

["alpha"]=1, // ["string"],还可以这样

npoints=4,  //注意以上的都不在sequence 里面,下面的才是,注意每个元素的, 逗号隔开不能少
{x=0, y=0}, -- polyline[1]
{x=-10, y=0}, -- polyline[2]
{x=-10, y=1}, -- polyline[3]
{x=0, y=1} -- polyline[4]

,//the last comma is validate too


}

print(polyline[2].x) --> -10
print(polyline[4].y) --> 1


Finally, you can always use a semicolon instead of a comma in a constructor.
I usually reserve semicolons to delimit different sections in a constructor, for
instance to separate its list part from its record part:
{x=10, y=45; "one", "two", "three"}, ; and ,其实没区别,只是我们可以当作不同section 来看而已


Exercise 3.1: What will the following program print?
for i = -10, 10 do   --其实这里也告诉你这么写for 循环了
print(i, i % 3)
end

-10     2  // % 模运算的符号取决于第二个操作数
-9      0
-8      1
-7      2
-6      0
-5      1
-4      2
-3      0
-2      1
-1      2
0       0
1       1
2       2
3       0
4       1
5       2
6       0
7       1
8       2
9       0
10      1


Exercise 3.2: What is the result of the expression 2^3^4? What about 2^-3^4?

2^3^4=2^(3^4)=2.4178516392293e+024

2^-3^4=4.1359030627651e-025=2^(-3^4)

All binary operators are left associative, except for ‘^’ (exponentiation) and ‘..’ ,靠如果不注意还以为是(2^3)^4.,而且^还是最高priority.
(concatenation), which are right associative.


Exercise 3.3: We can represent a polynomial anx^n + an-1x^n-1 + : : : + a1x^1 + a0
in Lua as a list of its coefficients, such as {a0,a1,...,an}.
Write a function that receives a polynomial (represented as a table) and a
value for x and returns the polynomial value.


frist we need how to write a for loop for the table.ie:

tableList={
"first one",
"second one",
"third one",
"last one"
};
for k=1,#tableList do
 print(tableList[k]);
end


==============

polynomial={2,3,4,5};
function countPolyNomial(potalbe, paraX)
    result=0;
    for plen=1,#potalbe do
          result=result+potalbe[plen]*paraX^(plen-1) --.notice that in Lua no += operator
     end
     return result;
end

cpcount=countPolyNomial(polynomial,3);
print(cpcount);


Exercise 3.5: How can you check whether a value is a boolean without using

the type function?

function isItABoolean(pp)
     result=pp==false or pp==true;
     if result then
     print("this is a boolean value");
      else
         print("not a boolean value :"..type(pp));
        end
end

isItABoolean(false);

// true==true ,false==false, 真 ,也就是说true, false  自己跟自己可以比较,,
  5==true, ""==true ,nil==false, 都不是真,(因为比较的是地址了 ),

but if i write

 if 5 then

  print("5 is test as true");

end;



Conditional tests (e.g., conditions in
control structures) consider both the boolean false and nil as false and anything
else as true.  all logical   operators consider both the boolean false and nil as false, and anything else
as true.  ,这个case 指的是在control structure 里面作判断。





Exercise 3.7: What will the following script print? Explain.
sunday = "monday"; monday = "sunday"
t = {sunday = "monday", [sunday] = monday} -- --t={sunday = "monday", "monday"="sunday"}; 把等价table 写出来就不容易错了
print(t.sunday, t[sunday], t[t.sunday]) --〉monday  sunday  sunday,  print 里面加逗号,打印结果是空格隔开














































































 
















评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值