Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 3 Current »

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:

function FOO(T)
   local Data = T.data
end

Then to call this function we have:

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.

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:

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:

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:

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
  • No labels