开发者

Strange logic in Lua script?

I can't seem to grok the way Lua ev开发者_如何学Goaluates 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?


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.


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


I did not try this, but I think not has a higher precedence than ==, resulting in

if ((not 41) == 42) then

... and obviously the result of the not-operator (either true or false) is not equal to 42.


In this context of your example the 'not' would not be treated as a boolean but as a reversing operator. Boolean example when no arithmetic operator- 'if a' means the result is true when the testing of condition, status, event or switch 'a' is satisfied, 'if not a' means the result is true when condition, status, event or switch 'a' is not satisfied. When a condition statement has an arithmetic operator and a second value then 'not' is slightly different and the test is against a specific value as a variable or a literal, like 'if a not = 42' as it is a condition operator and not a boolean operator and the truth table may have different entries.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜