Lua functions pass by reference

Hello,

I was curious whether lua has a way to pass functions as reference. I’m making a simple OOP structure for destructable parts, where several types of parts can destruct in different ways. I spawn those parts using a table of part templates. I could add a destruct function to the template, but I’m worried about potential memory overhead if that function is passed as a value. I’d like to avoid inheritance if possible.

If I just pass the whole template table and access the function from the table itself (not assigning it to another local variable) would it still be passed as value?

Lua only treats strings, numbers, bools and nil as constants - they can only be treated like values and they are always the same (for the most part). Functions, tables, threads and userdata objects on the other hand are interpreted as references due to their volatile nature.

1 Like

Oh okay, guess I read the lua documentation wrong. So let’s say I have a function f and I assign it to 2 other variables

local a = f
local b = f 

there will only be one f instance in memory while a&b contain a reference?

Mostly correct, but two things: first, strings aren’t literals, they are immutable like numbers, booleans and nil, but they are more complicated than the last three mentioned datatypes. For example, strings are garbage collected while numbers/booleans aren’t.
Second, functions and threads don’t really play a role in this, functions are immutable in the sense that the closure (upvalues) or its environment (globals) aren’t changed, and threads are just threads, you can’t really change anything about them. But yes, a reference is kept of them, but since you can’t mutate anything about them, having a reference is kind of pointless.

And actually, the string garbage collection might bring up something else, a reference of the string is perhaps kept, it’s not pass by value. Lua objects, including strings, get garbage collected if nothing points to them. A string "hi" for example can have multiple variables pointing to it.

local str1 = "hi"
local str2 = "hi"

It would make total sense if that’s the case, because let’s say you did

local str1 = "hi"
local str2 = "hi"
str1 = nil

I doubt there are two "hi" strings in memory, just one, and it’s not garbage collected yet since str2 still points to it. This might be confusing since strings are immutable in lua thus it isn’t as intuitive, and only way to confirm is reading lua’s source.

5 Likes

You can easily test this by doing:

print(tostring(a) == tostring(b))

Thanks for the extra information.
My point of having a reference is so I can easily construct destructable part behavior templates and load those into another script containing different types of destructable parts, knowing how each part should react to damage.

1 Like

Yes, you can pass functions by reference:

3 Likes