Expected Behavior
I expect this to print “nil” if “Bla” does not exist.
Actual Behavior
It is blank, as if I typed print().
In Lua, there is a difference between void and nil:
local function returnsVoid()
return
end
local function returnsNil()
return nil
end
print(returnsNil()) -- prints nil
print(returnsVoid()) -- is empty
This is confusing when a return value is expected. I was using print(instance:GetAttribute(attributeName)) to see what the value was, and my first thought was that it was an empty string, rather than non-existent.
Workaround
Assigning to void gives it a name, so this works:
local value = instance:GetAttribute(attributeName)
print(value)
Issue Area: Engine Issue Type: Other Impact: Moderate Frequency: Rarely
I agree. It should return nil if it doesnt exist. Instead its behaving like a TextLabel’s Text property containing no text. This is troubling as we will have to not just check if its nil, but if its also an empty string. But perhaps someone would want to put an empty string in an Attribute? then perhaps a way to identify the Attribute’s purpose, like a setting. Because Attributes can be a string, number, boolean, etc…
Thanks for the report. For context, this issue is related to how we handle nil values in our reflection layer therefore you’ll find the same is true of other APIs. When I have a fix I’ll be sure to leave an update.
I know this topic is 2 months old but I kinda want to bring it to light again and especially thank Ozzypig for the neat trick they provided:
To get around this issue, I was doing:
local N = tonumber(Instance:GetAttribute("SomeString") or nil) or 1
but with that method I can just do:
local N = tonumber((Instance:GetAttribute("SomeString"))) or 1
which is a little bit simpler.
Normally when passing nil through tonumber() it wont error the script, but it does with GetAttribute() because it does not return nil as mentioned on the Developer Hub: link to page
Hopefully this is fixed soon so we dont have to use so many parenthesis.
My coworker ran into this bug today and lead us down a rabbit hole of weirdness to how Lua handles expressions in function arguments.
An expression like typeof(object:GetAttribute("Attribute")) should reasonably evaluate to “nil” in cases where Attribute is not defined on an Instance.
Edit: modified this post as I had a stupid typo in my code, apologies @Judgy_Oreo .
But: the debugger for watches is still buggy, if I add a watch for “a” it will say it’s a “void” in this case:
local x = {}
local a = x[“dsf”] → watch for “a” will be “void”.