syntax.us Let the syntax do the talking
Blog Contact Posts Questions Tags Hire Me

Question:
In Lua how to decorate a function?

In Lua how do I decorate a function to widen its abilities?
-- ~/ks/b/lua/decorate_f.lua

function vehicle_topspeed(horsepower)
  return horsepower/3
end

mycar_topspeed = vehicle_topspeed(400)
print(mycar_topspeed)

-- For boats
-- Key idea here, point to function with local variable:
local vehicle_topspeed_land = vehicle_topspeed

-- Now use the old variable name:
vehicle_topspeed = function(horsepower)
  -- Use the local name to access the old function:
  return (vehicle_topspeed_land(horsepower) / 4)
end

myboat_topspeed = vehicle_topspeed(400)
print(myboat_topspeed)
The above example is a bit weak but it is a step in the right direction.

The next step would be to enhance the decorated vehicle_topspeed() so it takes an optional vehicle-type variable.

If vehicle-type is nil, branch to logic which calls vehicle_topspeed_land().

syntax.us Let the syntax do the talking
Blog Contact Posts Questions Tags Hire Me