workaround for nil is false & arg defaults

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

workaround for nil is false & arg defaults

John Belmonte-2
It's not fun that nil and false are the same thing... it's been debated well enough on this
list.  Anyway here is a common problem along with a workaround.

Let's say we want a function to have an optional boolean flag.  Lua presents no problems as long
as you want the default to be false:

    function test1(x, flag)
      local flag_message = flag and " (flag set)" or ""
      print("test1: "..x..flag_message)
    end

    test1(5)
    test1(5, nil)
    test1(5, not nil)

Now what if you want the default to be true?  One way is to invent your own (non-nil) values for
true and false, but then you can't feed the result of real boolean expressions into your
function.  Another way is with some vararg trickery (not elegant in my opinion):

    function test2(x, ...)
      local flag = (arg.n < 1) or arg[1]
      local flag_message = flag and " (flag set)" or ""
      print("test2: "..x..flag_message)
    end

    test2(5)
    test2(5, nil)
    test2(5, not nil)


-John