I wrote a short code to test a statement from the book I'm studying through, Programming in Lua (3rd Edition).
The statement on page 10 of the translated text is as follows: Conditional tests (for example, conditions in control structures) consider both the Boolean valuefalse
and nil
as false
and everything more like true
.
function test (a)
if a then print(type(a).." '"..tostring(a).."'".." corresponde a verdadeiro")
else print(type(a).." '"..tostring(a).."'".." corresponde a falso") end
end
print("Teste 1: ")
test(true)
print("\nTeste 2: ")
test(0)
print("\nTeste 3: ")
test("")
print("\nTeste 4: ")
test("a")
print("\nTeste 5: ")
test(test)
print("\nTeste 6: ")
test(test("masuia"))
print("\nTeste 7: ")
test(false)
print("\nTeste 8: ")
test(nil)
print("\nTeste 9: ")
test(a) -- variável 'a' não foi inicializada, então corresponde a nil
When I ran the code, I received the following result on the console:
Teste 1:
boolean 'true' corresponde a verdadeiro
Teste 2:
number '0' corresponde a verdadeiro
Teste 3:
string '' corresponde a verdadeiro
Teste 4:
string 'a' corresponde a verdadeiro
Teste 5:
function 'function: 000000000026F2A0' corresponde a verdadeiro
Teste 6:
string 'masuia' corresponde a verdadeiro
nil 'nil' corresponde a falso
Teste 7:
boolean 'false' corresponde a falso
Teste 8:
nil 'nil' corresponde a falso
Teste 9:
nil 'nil' corresponde a falso
Why does the "Test 6" result occur? According to the statement of the book, the test was not supposed to be false, since the last parameter was not the boolean value false nor nil
? Also, where did this second row come from?