Search code examples
lua

Does returning a pre-created table create a new one?


If I run this piece of code

MyTable = {}
function SomeFunction()
 return MyTable
end
SomeFunction()

Does it create a new table or return a pre-created table?

So far, I don't know exactly how I can check that with current methods. I know


Solution

  • Let's walk through the execution of the code:

    1. A new table is created: {}
    2. The new table (or rather, the reference to it) is assigned to the global variable MyTable
    3. A function is defined.
    4. The function is assigned to the global variable SomeFunction
    5. The global variable SomeFunction is accessed
    6. The result of the access is called
    7. We enter the execution of SomeFunction:
      1. The global variable MyTable is accessed
      2. The result of the access is returned - this will be the table (or rather, the reference to it) initially created

    So no, SomeFunction will not copy MyTable - it will return the reference to the already existing table. For the creation of a table inside SomeFunction, you would need a table constructor inside SomeFunction: function SomeFunction() return {} end would create a new table each time it is called.

    As Ramon has pointed out, you can use print(MyTable) to print the reference to a table (e.g. to verify that it doesn't change).

    You might want to localize MyTable to make it an "upvalue" rather than a "global variable".