Passing variables through Pcall not working

I am having a bit of trouble with this Updating my DataStore. I am trying to update the value of a table of booleans, but it is not passing the variable for the boolean through the pcall function. Here is my code (if there is a better way to write this, by all means, please correct me.)

local function SetData(player)
	
	if not EndingsData then
		
		for i, Ending in ipairs(EndingsTable) do
			
			local success, err = pcall(function()
				EndingsData:SetAsync(player.UserId..Ending.Name, Ending.Value)
			end)

			if success then 
				print("Successfully set data")
			else
				print("Error")
				warn(err)
			end

		end
		
		
	else
		
		local function UpdateData(Ending)
			
			local NewValue = Ending.Value
			
			return NewValue
			
		end
		
		for i, Ending in ipairs(EndingsTable) do
			
			local success, err = pcall(function()
				
				EndingsData:UpdateAsync(player.UserId..Ending.Name, UpdateData(Ending))
				
			end)

			if success then 
				print("Successfully set data")
			else
				print("Error")
				warn(err)
			end

		end
		
	end

end

The output keeps saying “attempt to index nil with name” which means the variable is not getting through. However, when I print the variable outside of the pcall, it works fine. Any and all help is appreciated!

1 Like

“Ending” in your pcall is shadowing the other variable. Remove “Ending” from your pcall function and it should work

2 Likes

Sorry, I wrote the code wrong. the value of the ipairs loop should be called ending (it’s changed now). If I don’t have the Ending variable in the pcall function, it says that it cannot pass value to function.

1 Like

Get rid of the Ending inside of the parentheses is what he is saying. And it doesn’t need to be passed, pcall can read variables from the scope above. If you really want to make the most of pcall, you can also do this.

local success, value = pcall(EndingsData.SetAsync, EndingsData, player.UserId..Ending.Name, Ending.Value)
3 Likes

I changed the code, but now it says “unable to cast value to function” Thanks for the help!

1 Like

Eh I’m tired. Ignore my second code block and just do what I recommended above it.

2 Likes