Skip to main content

Using a table as a function argument

This is a design 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 one parameter 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 a second 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