Loadstring() In A For Loop

  1. **What do you want to achieve?

Trying to make a for-loop function that runs the code that was given in the parameter of the function call, in a for-loop.

  1. **What solutions have you tried so far?
local Players = game:GetService('Players')


local function ForLoop(Table,Code)
	
	for _, v in Table do
		loadstring(Code)()
	end
end

ForLoop(Players:GetPlayers(),"print(v.Name)")

But the error says that I am attempting to index nil with Name.

How can I achieve this?

Update your code to pass in a paramater for “v”. Loadstring runs in a totally different environment.

loadstring(Code)()(v)
ForLoop(...,"return function(v) print(v.Name) end")
1 Like

Oh wow that worked thanks. So you can put in a parameter in loadstring() by doing loadstring(…)()(whatever)

As long as theres a return function(whatever) at the beginning of the loadstring code to make sure the function returned by loadstring() returns another function allowing you to access whatever you need to by calling that function.

3 Likes

Do you know if it’s possible to go further and maybe write a function of some sort so you wouldn’t have to write the (“return function(v) end”) each time?

Yes it is possible and I have made code for that before.

1 Like

Can you show an example on how?

Why are you using loadstring here?

What is the second parameter for? the (…)? to call it wouldn’t it just be FunctionName("print(“Hello”))?

The second parameter is the variables you want to put in the loadstring environment.

1 Like
local function ForLoop(Table) 	 	 
   for _, v in Table do 		 
       print(v.Name)
   end
end

Will do the same thing but simplier.

That is not what i am trying to do at all.

Thats exactly what you are trying to do judging by your code.

I just realised that the code i sent would not work. Sorry

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