Reading — step 1 of 5
Learn
~1 min readFunctions
Functions are first-class. Two equivalent syntaxes:
function add(a, b)
return a + b
end
-- same as:
add = function(a, b)
return a + b
end
Prefer local function for module-private helpers — same as local x = function ....
Multiple return values are first-class. Lua functions can return any number of values, and assignments take what they need:
function divmod(a, b)
return a // b, a % b
end
local q, r = divmod(17, 5) -- q=3, r=2
Variable arguments with ...:
function sum(...)
local total = 0
for _, v in ipairs({...}) do
total = total + v
end
return total
end
print(sum(1, 2, 3, 4)) -- 10
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…