Rrunr
Rrunr

Reputation: 35

If Statements in Lua

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 then
            h.Health = 0
        end
    end

    script.Parent.Touched:Connect(onTouched)

Upvotes: 2

Views: 8558

Answers (3)

Piglet
Piglet

Reputation: 28940

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.

Upvotes: 1

luther
luther

Reputation: 5544

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.

Upvotes: 3

Yoav Haik
Yoav Haik

Reputation: 96

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).

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

It's like that in script languages.

Upvotes: 1

Related Questions