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)
What is the issue?
This sample code prints “nil” since it can’t see the object inside the function?
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.
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.