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.


发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注