Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange logic in Lua script?

Tags:

lua

I can't seem to grok the way Lua evaluates boolean values.

Here is a trivial snippet intended to demonstrate the problem:

function foo()
  return true
end

function gentest()
   return 41
end

function print_hello()
  print ('Hello')
end


idx = 0

while (idx < 10) do
 if foo() then
    if (not gentest() == 42) then
       print_hello()
    end
 end
 idx = idx +1
end

When this script is run, I expect to see 'Hello' printed on the console - however, nothing is printed. Can anyone explain this?

like image 973
oompahloompah Avatar asked Apr 25 '26 17:04

oompahloompah


2 Answers

Inside your while loop, you should use the not outside the parenthesis:

while (idx < 10) do
 if foo() then
    if not (gentest() == 42) then
       print_hello()
    end
 end
 idx = idx +1
end

(gentest() == 42) will return false, then not false will return true.

(not gentest() == 42) is the same as ( (not gentest()) == 42). Since not gentest() returns not 41 == false, you will get false == 42, and finally that returns false.

like image 110
Fábio Perez Avatar answered Apr 27 '26 06:04

Fábio Perez


Try not (gentest() == 42). .

like image 21
lhf Avatar answered Apr 27 '26 06:04

lhf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!