Why doesn't this table pass by reference? (SOLVED)

#1

I’ve created a sample project here which demonstrates a Lua module where the table pass by reference is disregarded. See test.lua module. If I modify the function to return t2 and store it to t then the function behaves as expected. Can anyone explain this to me?

My Project.zip (87.3 KB)

0 Likes

#2

To save everyone some time:

function scrub_tombstones(t, tombstone)
	local t2 = {}
	for k,v in pairs(t) do
		if v ~= tombstone then
			t2[k] = v
		else
			pprint("tombstone scrubbed")
		end
	end
	t = t2
end

t = {1, 2, 3, 4, 5}
scrub_tombstones(t, 3)
pprint(t)
2 Likes

#3

This is a classic example of variable shadowing. The first argument “t” in scrub_tombstones is local to the function and “shadows” the global variable “t”. When you do t = t2 you replace the local reference and not the global “t” declared outside the function.

This is also an example of why you should avoid using global variables (and functions!).

3 Likes

#4

Thank you, this is something I have to watch out for :blush luckily I have been testing things so I caught this before it became an issue. It’s one thing that bothers me slightly about Lua though for certain. I’ll try to write my code in a more functional style to avoid stuff like this.

0 Likes