Getting the variable from another function

Just like the title says, I’m trying to get the variable from a function outside of it.

Basically what I’m trying to do.

Thanks,

  • Luke
3 Likes
local mass = getMass()

?

That is the purpose of the return function. To return a value. Simply do:

local function giveMeOne()
    return 1
end

local one = giveMeOne()

print(one) --> 1
4 Likes

You’re returning the value of “mass” at the end of the function named “getMass()” anyway so all you need to do is call the function named “getMass()” and assign it to a variable, like so:

local mass = getMass()

1 Like

Hi!

While others have already explained how you can store the returned variable, I feel like it’s been missed that your function is kept being defined inside your while-loop. The loop is endlessly calling this block:

do
    local function logic() ... return x end
    local x = logic()
end

And once end is reached function is out of scope, rendering it unreachable in the memory and scheduling it for garbage collection continuously.

Analogy: creating a pencil again and again just to draw a line instead of reusing the created one.

local function GetMass(model)
    ...
    return mass
end

while true do
    local mass = GetMass(object)
    task.wait(1)
end

Getting mass of a single object continuously shouldn’t be necessary either. Instead, you could just get the mass and store it in order to reuse it. If you are expecting objects to be added or removed from the model, then you could recalcualte on demand.

model.DescendantAdded:Connect(function(descendant)
    if not descendant:IsA("BasePart") then return end
    GetMass(model)
end)
model.DescendantRemoved:Connect(function(descendant)
    if not descendant:IsA("BasePart") then return end
    GetMass(model)
end)

Lastly, in case you still intend to calculate mass rapidly, you should consider the following two changes:

  • Removing abstraction (instead of using a function just calculate in a loop). Each time you call a function it’s added to the call stack, so avoiding wrapping in function would be a small step towards better performance.

  • You might want to consider using RunService.Heartbeat connection, since that reduces script activity a little in comparisson with task.wait(), respectively RunService.Heartbeat:Wait(). Ideally, you would use the above, event based approach. Either way, avoid wait().

(The following article explains why spawn(), delay() and wait() are to be avoided in newer work.)

EDIT.
And here’s the documentation about return: https://education.roblox.com/en-us/resources/returning-values-from-functions.

3 Likes

Use the return keyword

function add(a, b)
  return a + b
end

local x = add(2, 3) -- 5 (try changing the + to a * to see what happens to this print statement)
print(x)