Returning says a Instance is nil

hi, i was working at my DataStore sistem but at the end, returning dont want to return the Instance

a exaple of what i made:


function module:CreateValue(plr,name,Item,Type)
      local val = Instance.new(Item..'Value')  ; val.Name = tostring(name)
      warn(val.Name)  -- It warns val's name
      return val
end

local val = module:CreateValue(nil,'Money','Int',nil)
warn(val.Name) -- error: val is a nil Instance

why it says val is a nil Instance?

Looking at your code it seems like you have an unfinished string in the module script:

function module:CreateValue(plr,name,Item,Type)
      local val = Instance.new(Item..'Value')  ; 
      val.Name = tostring(name)
      warn(val.Name)  -- It warns val's name
      return val
end

This may help

that is only an example, the original code is diferent

Umm… this works for me but one reason why this might give you an error is because i believe you aren’t setting the parent to anything

this is setting the parent:


function module:SetParent(parent,name,object)
	local val = module:CreateValue(nil,name,object,'set')
	if not parent.Name == 'leaderstats' then
		error('DataStore3: u can only add values to players!')
	else
		val.Parent = parent
	end
end

Potential issue: operator precedence.

not parent.Name == 'leaderstats'

This is

(not parent.Name) == 'leaderstats'

So it’s comparing false to leaderstats which is still false.

Don’t reinvent the wheel, and instead use the ~= operator:

if parent.Name ~= 'leaderstats'

By the way instead of

if not x then
    error(msg)
end

assert exists.

assert(parent.Name == "leaderstats", "DataStore3: parent must be a leaderstats!"). If the first argument is falsey, it will output the second argument as an exception. The second argument defaults to "assertion failed!". If it’s truthy, assert won’t throw an exception, it will return the first argument

I was unable to reproduce your error with the script you have provided. Is something else in another part of your script causing this error to occur in this part of the script? Are you calling the function correctly with the correct parameters?

In the script that you have provided there doesn’t seem like there is anything wrong with it other than a bit of tidying up:

function module:CreateValue(plr,name,Item,Type)
	local val = Instance.new(Item..'Value')
	val.Name = tostring(name)
	warn(val.Name)  -- It warns val's name
	return val
end

local val = module:CreateValue(nil,'Money','Int',nil)
warn(val.Name) -- error: val is a nil Instance

i done it… idk what the problem was but assert helped me