I know what a function is, but I don’t know how to use it
Two days ago, I knew how to use it and know everything about it, but I am now 40 years old, which means I am forgetting =(
I know what a function is, but I don’t know how to use it
Two days ago, I knew how to use it and know everything about it, but I am now 40 years old, which means I am forgetting =(
You can execute code inside with additional parameters:
function do(msg)
print(msg)
end
do("hi")
What?
This is my real age, I know you don’t believe
So, since you know what a function is, I’ll just write code snippets with explanation.
local function printSomething(thing)
print(thing)
end
printSomething("Hello, World!") -- Prints `Hello, World!` to the output, very simple
Now, let’s make it print n
things
local function printThings(...) -- `...` indicates inf parameters!
print(...)
end
printThings("Hello, World!", "\n", "\t\t", "Hello, World!") -- prints `Hello, World!<new line><new line> <increase indent><another increase>Hello, World!`
Now, returning.
local function sum(a, b)
return a + b
end
print(sum(1, 3)) -- 4
Challenge!
Change the sum
function to accept n
parameters and return the sum of all of them, reply with your try and I’ll help u with it, you can also pm if that’s better for you.
now, table with functions.
local t = {} -- Just making a table here
-- Let's add a function now, lets do the `sum` function.
function t.sum(a, b)
--[=[
notice how we didn't include `local`, this function is in a table
so writing local before it will actually error.
]=]
return a + b
end
print(t.sum(1, 3)) -- 4
This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.