i have a function in Lua that operates on a table, repeatedly adding entries to the table:
function DoStuff()
local table = {};
for i = 1, 1000 do
local name, value = GetSomething(i);
if (CheckSomething(name, value))
table[name] = value
end;
end;
end;
i know this is fast; Lua has a good hash table algorithm. But now i need to split out part of my function, so i may unit test it:
function DoStuff()
local table = {};
for i = 1, 1000 do
local name, value = GetSomething(i);
--split out checking so it's testable
table = ParseTheThing(table, name, value);
end;
end;
i know that Lua does not support passing paramters by reference, instead if i need to add an item to my table, Lua will make a copy and i must return that copy:
--Core checking function
function ParseTheThing(table, name, value)
if (CheckSomething(name, value))
table[name] = value
end;
return table;
end;
So it seems to me that every time i call CheckSomething Lua will create another table, that needs to be garbage collected.
Or maybe not. Maybe Lua does support passing parameters by reference, and i can simply call:
ParseTheThing(table, name, value);
--Core checking function
function ParseTheThing(table, name, value)
if (CheckSomething(name, value))
table[name] = value
end;
end;
Will Lua’s garbage collector be forced into doing a lot more work if i refactor my code as i have done?
Notes:
- Don’t confuse the simplified example used in the question with the question i’m asking.
- i don’t have any way to measure memory usage, or number of collections, so i cannot try it.
The term “by reference” is overloaded, causing a lot of confusion (especially in the Java world where I’ve seen people refuse to acknowledge that one of the meanings even exists).
Passing by reference can mean:
Passing the location of an object in memory, rather than the object itself. This is what is meant by “pass by reference” in C. In this sense, Java does pass by reference, and so does Lua for many of its types (userdata, tables, etc.).
An alias for a variable, such that any modifications to the alias is reflected in the original. This goes beyond simply not passing by value; if the variable holds a location of an object, you can assign a different location through the alias. You can’t do this for #1, where you pass a reference to an object, not a variable. These types of references are supported in C#, C++, etc., but not C or Lua.
More simply:
Just pass the table — a reference, not a copy, is passed.