Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
-1

Help with running a function?

Asked by 9 years ago

So I have this code that prints "Fired Missile #1/#2") is there a way to run a function when Missile #1 is fired and then make it run another function when Missile #2 is fired?

local function missileFactory(id)
 return {Fire = function()
  print("Fired missile #"..id)
  return true
 end}
end

local Missile = {
 missileFactory(1),
 missileFactory(2),
 {Fire = function()
  print("Out of missiles!")
    resetFire()
    return false
end}
}

local nextMissile = 1

function resetFire()
    print 'reset'
 nextMissile = 1
end


function fire()
    print 'fire'
 local fired = Missile[nextMissile]:Fire()
 nextMissile = nextMissile + 1

 return fired -- Pass on the result of Fire(). We could not increment nextMissile if it fails, but I'm lazy.
end

1 answer

Log in to vote
0
Answered by
modFrost 130
9 years ago

Oh okay, so you can use a debug variable to test which missile to fire

local CurrentMissile = 1

local function Fire()
    print("Fire")
    CurrentMissile = CurrentMissile == 1 and 2 or 1
    if CurrentMissile == 1 then
        print("Fired Missile #1") -- You would call the first function
    elseif CurrentMissile == 2 then
        print("Fired Missile #2") -- You would call the second function
    end
end
Ad

Answer this question