In all other programming languages I've encountered, if statements always require a boolean to work, however in Lua the following code does not contain any errors. What is being checked in this if statement if both true and false statements can't be made? How can you only check "if (variable) then"? I am new to programming and currently working with Roblox Studio, any help would be very appreciated.

function onTouched(Obj)local h = Obj.Parent:FindFirstChild("Humanoid")if h thenh.Health = 0endendscript.Parent.Touched:Connect(onTouched)
3

Best Answer


Most languages have their own rules for how values are interpreted in if statements.

In Lua, false and nil are treated as false. All other values are treated as true.

if h == nil (null)

So if it couldn't find a humanoid in the object that touched the script's parent, it will be false (null), otherwise true (not null).

Soif [ObjectName] thenequals to if [ObjectName] != null then
*Only valid for objects (non primitive values)

It's like that in script languages.

if h then end

is basically equivalent to

if h ~= nil and h ~= false then end

In Lua all values that are not nil or false are considered to be logically true.

if h then end is usually used to check wether h is not nil. So if code depends on wether h has been defined you put it in a condition like that.

In your example h is being index. indexing nil values is not allowed. So befor you index it you should make sure it isn't nil to avoid errors.

Checking return values of functions is good practice.