How to Define a Variable Within A Function Then Access it Outside?

  1. What do you want to achieve?
    I want to define a variable like this:
_G.highlight = nil

local function()
     _G.highlight = object
end

print(_G.highlight)
  1. What is the issue?
    This sample code prints “nil” since it can’t see the object inside the function?

  2. What solutions have you tried so far?
    I’ve tried different solutions with _G and defining the variable in difference places (parametre in the function), but it doesn’t work. Is it impossible to make this work?

*Note: I’m very inexperienced in coding, so please correct me on misunderstandings. :face_holding_back_tears:

local foo = nil
local function bar()
    foo = "Hello World!"
end

print(foo) --> 'nil'
bar()
print(foo) --> 'Hello World!'

In order for a global variable to be redefined by a function, you have to call the function first

1 Like

You should take a look at scopes Scope | Documentation - Roblox Creator Hub

1 Like

Thank you you guys for the help, but I think a for loop in my code is messing with the scope, and I’m not sure how to fix it.

Let me provide a more specific example for my use case.

local highlight = nil

local function Highlight()
    local objects = {}
     for_, object in ipairs(objects) do
       highlight = Instance.new(“Highlight”)
     end
end


Highlight()
print(highlight)

This returns nil unless I define it before the for loop (which won’t work for this case).

That’s because there’s nothing in your objects table, so of course since there’s nothing to loop through, the highlight assignment is never ran. Also, can you tell us what you’re trying to accomplish? There might be better ways.

Sorry, that was pseudocode to help others understand my use case a bit better (my code is so ridiculously long I didn’t think anyone had the time to read through every detail).

I found that returning the highlight variable fixed the issue.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.