Function Composition

You have already defined functions, passed parameters, returned values, and practiced safe variable scope. In this lesson, we will combine those skills to design a small, clear workflow using multiple functions. Think of this as a reminder of earlier ideas, but now applied together: small, focused functions that compose into a complete solution.

Build Small Helpers: sum_prices and apply_discount

Explanation: This helper function iterates through a list of item prices with ipairs, adds them up into total, and returns the sum. Using local keeps the function and its variables scoped and safe.

Explanation: This function does one thing: subtract a discount from a total and return the result. Clear inputs, clear output, no side effects.

Compose Functions: final_price

Explanation: Here, you see function composition in action. We first compute the total using sum_prices, then pass that result into apply_discount. This keeps each function simple, while the combination solves a larger task.

Run the Plan

Explanation: We define our inputs as local values, call final_price to run the whole workflow, and print the result using string concatenation. The output shows that 100 + 200 + 50 = 350, and 350 - 30 = 320.

Summary and Next Steps

You combined small, focused functions into a clean pipeline:

  • sum_prices totals a list.
  • apply_discount adjusts the total.
  • final_price composes both to produce the answer.

This is how you build bigger programs — by composing small parts. Head to the practice section to apply these ideas and strengthen your ability to design modular Lua code.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal