Eliot’s Tips and Tricks

Not equal to

This was one aspect of Lua’s syntax that confused me when I was learning the language. I even had a ticket in our bug tracking system suggesting we add “!=” to the Lua language.

There is another gotcha with comparison operations in Lua. If you compare two variables that point to different types then they are not considered equal. Notice in this example code that the not equal operation in line 12 is not triggered. This is because a comparison is being made between a string and what we call a “node tree” in the Translator:

Here is the code to copy:

local function trace(a,b,c,d) return end

function main()
   local X = xml.parse{data = "<patient name = 'Fred'></patient>"}
   compare(X.patient.name)
end

function compare(name)
   -- comparison between node tree and string is not equal
   if name ~= 'Fred' then 
      trace(name.." isn't here") 
   else
      trace('Hello '..name) 
   end

   -- convert node value to a string and the name matches
   if name:nodeValue() ~= 'Fred' then 
      trace(name.." isn't here") 
   else
      trace('Hello '..name) 
   end
end
Tagged:

One Comment

  1. Pingback: Will You Share Your Code? - iNTERFACEWARE Inc.

Leave A Comment?

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.