t1a09: Functions by Innes

Good reference to JavaScript functions

Functions organize code. They can be called to run code multiple times. Functions can also receive information through parameters and return results.

Example 1: Basic Function

This function reads the two input values, adds them, and returns a sentence.

JavaScript: function myExampleFunction() { let myIn01 = parseInt(document.getElementById("myText01").value); let myIn02 = parseInt(document.getElementById("myText02").value); let mySum = myIn01 + myIn02; let myReply = myIn01 + " + " + myIn02 + " = " + mySum; return myReply; } Luau: local function myExampleFunction() local myIn01 = getNumber("myText01") local myIn02 = getNumber("myText02") local mySum = myIn01 + myIn02 local myReply = tostring(myIn01) .. " + " .. tostring(myIn02) .. " = " .. tostring(mySum) return myReply end

Example 2: Function with Parameters

This function receives the two numbers through its parentheses. It doesn't need to read the HTML inputs itself.

JavaScript: function addNumbers(myIn01, myIn02) { let mySum = myIn01 + myIn02; return mySum; } let answer = addNumbers(3, 6); Luau: local function addNumbers(myIn01, myIn02) local mySum = myIn01 + myIn02 return mySum end local answer = addNumbers(3, 6) print(answer)

Input Numbers





Test the Functions

Basic function result appears here.
Parameter function result appears here.

Luau Code Editor

Edit the Luau code below and click Run Luau. Both functions are included.


Luau Output