How can a function know the name of the variable that its return values were added to?

Imagine I have a table that looks like this:

local MyTable = {
  MyFunctionResult = MyFunction("Some Stuff")
}

Is it possible for MyFunction to know the name of the variable I added it’s return values to, which is MyFunctionResult?

You could change behavior making it call twice, and through condition have it determine a second branch of execution.

Without context for use I can only jump to conclusions and can’t study in depth an optimal use for your case.

Still, your value is global, you shouldn’t have issues establishing what is going on inside the table.

It isn’t possible unless you tell the function the name (i.e. pass the name as an argument).

However… There is a black magic voodoo way. You could call string.dump on the calling function and parse the bytecode for where the call takes place, and find out which global or local variable the result is assigned to. But this should not be done and is very advanced.

1 Like

Im trying to make a module that lets you build a GUI like a tree:

local Gui = ScreenGui.new {
  Name = "hi",
  ResetOnSpawn = false
  -- more gui objects
}

But It would be nice if it could autodetect the name of the new ScreenGui from your variable’s name

1 Like

That’s just not feasible without interpreter support :frowning:

If nested though, you could iterate through the parent table and set every value’s name to the key.

I don’t get exactly what you mean
But for now I think I could have the module have a list of GUI’s that you can access instead of StarterGui / PlayerGui that’s made when you make a new GUI Object with the module

Thanks for your help tho!

I just realized those wouldnt have names too… since you’d still have to have a Name thing in the table
Well i’ll figure something out

So if you have a parent object with children, the children will belong to the parent’s table and be assigned a key. We need to make this key the childrens’ names. To do this we iterate over the parent table’s keys and values looking for children as the value. When we find one, we set it’s .Name to the key.

Old post but string.dump() was sandboxed out of Roblox Lua beforehand.