Variables in Lua hold values. A "value" is a piece of data that you can perform operations on.
Simple examples of values are numbers (5 or -3.7), strings ("cat" or ""). You can add, multiply, and do more to these. Lua also has tables which let you make lists of values {1, 2, 3} and dictionaries like {a = 1, z = 26}. You can ask for the value at a given key/index (calling indexing or subscripting) like t[1], or get their length, like #t, among other things.
It's probably not so obvious that functions in Lua are values.
Just like 3 is a value that can be added or multiplied, function(x) return x + 2 end is a value that can be called.
local f = function(x) return x + 2 end
print("Two more than", 3, "is", f(3))
If the above seems foreign to you, compare it to this code, which probably makes more sense:
local f = 2
print("Two more than", 3, "is", f + (3))
In the second snippet, we're just using + with f. In the first snippet, we're just calling f.
In fact, when you write
function dothing(a)
return a + 1
end
Lua rewrites this into
dothing = function(a)
return a + 1
end
When you write code like
object.Event:Connect(function(arg)
......
end)
notice that it's structured and awful lot like
object:FindFirstChild("Some Name")
ie, it's a method call where you're passing one value as an argument! That value is a function, which Roblox internally saves, and then (possibly repeatedly) calls later whenever the event occurs.
Why would I ever use a function as a value instead of just calling it like normal?
Well, handling events with :Connect is one example. But let's look at "pure Lua" examples.
Here's a detailed explanation of so called "higher-order functions". HOF is a fancy term that means "a function that takes a function as an argument". This tends to be scary and confusing to people new to this, but I think it's good to slow down and just remember that functions are regular values and so regular arguments. You just call() them instead of doing more familiar operations like + and -.