/
Using a table as a function argument

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:

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:

Contrast if we had written FOO this way:

 

Related content

IMAP Library
Read with this
Use a table as an argument to a function
Use a table as an argument to a function
More like this
Naming convention for table parameters
Naming convention for table parameters
Read with this
User data
User data
More like this
Meta tables
More like this
The core types of Lua
The core types of Lua
More like this