2

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)
Rrunr
  • 35
  • 1
  • 4

3 Answers3

3

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.

luther
  • 5,195
  • 1
  • 14
  • 24
1
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.

ouflak
  • 2,458
  • 10
  • 44
  • 49
Yoav Haik
  • 86
  • 1
  • 6
  • To clarify, do you mean that h will be assigned true/false based on whether or not a humanoid is found? If that is the case, in line 4, how can you set the health of a boolean to 0? – Rrunr Dec 25 '21 at 11:50
  • No sorry casting isn't the right word, it's bascially a shortcut for: `if [ObjectName] then` equals to `if [ObjectName] != null then`. only works for objects, for boolean it checks the value and for numbers I'm not so sure – Yoav Haik Dec 25 '21 at 12:00
1
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.

Piglet
  • 27,501
  • 3
  • 20
  • 43