5
I wrote a little code to test a statement from the book I’m studying, Programming in Lua (3rd Edition).
The statement, which is found on page 10 of the book, translated is as follows: Conditional tests (e.g., conditions in control structures) consider both the boolean value false
and nil
as false
and everything else 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 went to run 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 book’s statement the test was not to have false result, since the parameter passed was not the boolean value false nor nil
? Besides, where did that second line of the result come from?
I already have a certain understanding of functions and expressions (as well as pointers) thanks to my studies of other languages, but did not know that the Lua functions returned nil when no return was specified. Great answer and very well explained!
– Raul FuGaDe
Many languages do this, especially the dynamic ones, where you need to have value for everything to give more flexibility.
– Maniero