Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

The same concept works in Javascript which is described in more detail here.

This is a nice pattern in Lua to make it possible to add parameters to a function without needing to break backwards compatibility with older code.

Say we make a first version of a function and it takes two parameters like this:

Code Block
languagelua
function FOO(T)
   local Data = T.

...

data
end

Then to call this function we have:

Code Block
languagelua
FOO{data="MYDATA"}

Then we realize that we need a timeout, we can extend the function to support this parameter without needing to alter previous code calling this function. In fact we can code things in a way that adds a default.

Code Block
languagelua
function FOO(T)
   local Data = T.data
   local Timeout = T.timeout or 1000;  --This parameter defaults to 1000 if not present
end

So now our old code still works, but newer code can optionally pass in the new parameter:

Code Block
languagelua
FOO{data="MYDATA", timeout=4000}
-- This older call still works:
FOO{data="MYDATA"}

In fact the pattern allows us to remove parameters which are no longer needed and still not break old code that might be using those unneeded parameters:

Code Block
function FOO(T)
   -- We are no longer using the data argument
   local Timeout = T.timeout or 1000;  
end

Contrast if we had written FOO this way:

Code Block
languagelua
function FOO(Data, Timeout)
   -- We can still default Timeout
   Timeout = Timeout or 1000
end

-- But if we removed the Data argument then it will break existing code
function FOO(Timeout)

end

-- This breaks client code like this:
FOO("MYDATA") --This will result in an error