## 一个有趣的代码问题

OldNewThing发布了一篇很有意思的文章http://blogs.msdn.com/oldnewthing/archive/2010/01/20/9950638.aspx

#### The wrong way to determine the size of a buffer

A colleague of mine showed me some code from a back-end program on a web server. Fortunately, the company that wrote this is out of business. Or at least I hope they’re out of business!

`size = 16384; while (size && IsBadReadPtr(buffer, size)) { size--; }`

1）16384这个16K大小来的莫名其妙，当然不排除在某些特定软件设计中，最大就是这个大小。

3）这个计算得到的值未必正确。

allocated with LocalAlloc, use LocalSize. For HeapAlloc, use HeapSize. For GlobalAlloc, use GlobalSize，如果使用CoTaskMemalloc，可以先用CoGetMalloc拿到一个IMalloc接口，然后调用GetSize()

## Some interesting Lua code test

When I read the book <the ruby way>, I get some interesting code that need to run in Lua. (I will test following code in Lua5.14 for windows package.)

` 1: print( 5 % 3)`

` 2: print( -5 % 3)`

` 3: print( 5 % -3)`

` 4: print(-5 % -3)`

The result will be 2, 1, -1, -2.

` 1: if not nil then`

` 2: print("not nil")`

` 3: end`

` 4:  `

` 5: if not false then`

` 6: print("not false")`

` 7: end`

` 8:  `

` 9: if 0 then`

` 10: print("0")`

` 11: end`

` 12:  `

` 13: if "" then`

` 14: print("empty string")`

` 15: end`

The result will be "not nil", "not false", "0", "empty string", in Lua, only nil and false will be FALSE in condition checking.

` 1: for i = 1, 5 do`

` 2: print(i)`

` 3: i = i + 5`

` 4: print(i)`

` 5: print("")`

` 6: end`

OK, the result will be 1  6, 2  7, 3  8, 4  9, 5  10, you could see the index variable "i" is not changed for the for-loop, and you could assign new value (i=i+5) to it in the for range, but it will restore back to the loop index value again.

` 1: local x, y = {}`

` 2: print(x)`

` 3: print(y)`

` 4:  `

` 5: y = x`

` 6: print(y)`

` 7: table.insert(y, "aa")`

` 8: print(x[1])`

It will print like "table: 003CACB0" "nil" "table: 003CACB0" "aa".

Two thing need to note, local x, y = {} will only initialize the "x". Another is the y will have same address with x if x is a table, and insert to table y will cause x changes too. It seems like in c or c++ only copy the pointer address, not copy the value with the pointer.

## Howto install Lua5.14 in Debian

3) tar zvxf lua-5.1.4.tar.gz

4) cd lua-5.1.4

5) make linux

6) make linux install

7) test with "lua -v", should be 5.1.4.

That’s all!

## Lua 5.2 work1 浅谈

1）增加了bitlib这个操作bit的内置库，函数有

{"band", b_and},
{"btest", b_test},
{"bor", b_or},
{"bxor", b_xor},
{"bnot", b_not},
{"bshift", b_shift},
{"brotate", b_rotate},

3）几乎所有的ifndef xx都改成了if !defined(xx)，所有的ifdef xx改成了if defined(xx)

4）增加了两个opcode，TFORCALL以及EXTRAARG。

5）增加了一个IN语句，类似

IN exp DO block END

6）table库中加入pack以及unpack，去掉setn

7）其余的内部改动非常多，大部分源代码文件都有一些。