Question regarding function memory allocation

So a recent post I’ve come across made me perform the following test:

function constructor()
local self = {}

function self.blah()

end

return self
end


local cache = {}

for i = 1, 10 do
table.insert(cache, constructor())
print(cache[i].blah)
end

Interestingly enough, despite defining the function as a member of each individual table that gets allocated, it would seem to print the same memory address (assuming that’s what is actually printing, it would appear to be that way)

I’ve tried to find Lua documentation on this subject, but I can find nothing. Based on my tests, it would appear that function definitions are allocated at compile time, and then references to those predefined functions are used as opposed to dynamically allocating memory for a new function entirely.

Really not sure though. Would appreciate any clarification about this, thanks.

1 Like
function self.blah()

end

Is syntactic sugar for:

self.blah = function()
	
end

Unlike tables, functions are mutable and do not change state (cannot be used to track state). In this instance, the ‘blah’ key/field for each of the 10 ‘self’ tables points to the same lambda function, it does not need to be redefined 10 times as it can be held in memory and it will always contain the same body of code (regardless of the table it belongs to). This is just one of the many memory optimisations undertaken by Lua that are abstracted from the end user.

1 Like