Return Variables out of loop and if statements

Im trying to return a Variable which is an Entity out of a for loop in an if statement.

Example:



if 1 == 1 then
 for i = 1,1 do
  local Mob = ents.Create("npc_zombie")
 end
end

print(Mob)


I want to return Mob(The Entity)



if 1 == 1 then
 for i = 1,1 do
  local Mob = ents.Create("npc_zombie")
   return Mob
 end
 return Mob
end

print(Mob)


This is not working.

That’s not how returns work. You get return values from a function, which that is not wrapped in.

Ok, is there a way to use the Variable out of the loop and the statement?



function test()
	local res
	for i = 0, 100 do
		if i == 50 then 
			res = i 
		end 
	end 
	return res 
end 

print(test())


Do it like that

Your creating the variable localy inside the loop, that means it wont exist outside that loop. Instead just create it outside the loop:


local Mob
if 1 == 1 then
 for i = 1,1 do
  Mob = ents.Create("npc_zombie")
 end
end

print(Mob)


Looks like it is working thanks a lot guys.