Lua Fundamentals

Lesson 4 of 6

Functions and Scope

Functions in Lua are values, they can be stored in variables, passed as arguments, and returned from other functions, just like tables or numbers.

Defining and calling functions

Lua

Lua functions can return multiple values at once, something many other languages need a tuple or object to fake.

Scope with local vs. global

Lua

WARNING

Forgetting local silently creates a global variable, visible to your entire program (and, if you're embedded in a game or app, potentially to other scripts too). Get in the habit of typing local in front of every variable and function unless you deliberately want it global.

Functions as arguments

Lua

Passing an anonymous function(...) ... end directly as an argument is idiomatic Lua, this is exactly how callback-style APIs (like button click handlers in game engines) are typically used.

📝 Functions & Scope Quiz

Passing score: 70%
  1. 1.What happens if you assign to a variable without the "local" keyword inside a function?

  2. 2.A Lua function can return more than one value at a time.

  3. 3.The keyword used to define a function in Lua is ____.