Quote:
if string.match( "removepoison", spell ) ~= nil then
But I think that looks redundant. Any non-nil (or non-false) result is considered true, so my version is cleaner, IMHO. I think there's a big conceptual difference between testing for non-nil and testing for true. Nil means "no value", and that can be different from "false". You could imagine a ternary logic system of sorts where variables are true, false or unspecified.
Or, consider function variables. Imagine I have a function like so:
function f(flag)
if flag then
-- do something
else
-- do something else
end
end
Let's say you want flag to default to true. So, if f is called with no arguments (like just f()) the parameter will be nil.
You could write:
function f(flag)
flag = flag or true
if flag then
-- do something
else
-- do something else
end
end
However, this will prevent the value of "flag" from being negative. So, you could do:
function f(flag)
flag = (flag == nil and true) or flag
if flag then
-- do something
else
-- do something else
end
end
This way, if flag is nil, then you take the value true; otherwise, if flag is non-nil (so flag==nil is false) you will take the value of flag.
This is, incidentally, why I also prefer to sometimes leave in the "true" in if statements:
if foo == true then ... end
It makes more sense, I think, when you are looking at negation:
if foo == false then ... end
Here, your test will fail when foo is nil. Perhaps this is not what you want, and arguably you should be testing for nil to make sure you have a value in the first place.
All this to say that I think there's quite a conceptual difference between nil (i.e. unspecified) and false (i.e., well, specified to be false). |