Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 32 ยท Practice and Review

Lua Interview Questions

Common Lua interview questions with short answers: tables, nil vs false, 1-based indexing, closures, metatables, coroutines, errors and modules.

Lua interviews tend to circle the same handful of ideas. Almost everything in the language is built from one data structure, the table, plus a few small mechanisms layered on top: metatables for behavior, closures for state, coroutines for cooperative multitasking. If you can explain those clearly, and you know the traps that catch newcomers (1-based indexing, nil versus false, the length of a table with holes), you can handle most questions.

Each answer below is short enough to say out loud. Lua is not installed on this site, so real Lua code is shown in read-only blocks, and the runnable editors use JavaScript stand-ins that model the rule being discussed. They say so when they are a model. Practice by covering the answer, replying in your own words, and then comparing. If a point is shaky, follow the link back to the lesson.

Language basics

1. What kind of language is Lua?

Lua is a small, fast, dynamically typed, garbage-collected scripting language, designed to be embedded in a host program written in C (or another language). It has a register-based bytecode virtual machine, first-class functions with lexical scoping, and a single compound data type, the table. Games, Redis scripting, Neovim and many embedded devices use it. See Introduction to Lua.

2. Which types does Lua have?

Eight: nil, boolean, number, string, table, function, userdata and thread. type(x) returns the name as a string. Since Lua 5.3 the number type has two subtypes, integer and float, and math.type(x) tells them apart. userdata holds host (C) data, and thread is a coroutine, not an operating-system thread. See Variables and Types.

3. What is the difference between nil and false?

Both are falsy, and they are the only falsy values. But they are different values: nil == false is false. nil means "no value" and is what you get from a missing variable or table field. false is a real boolean value. Assigning nil to a table field removes the key; assigning false stores it. Everything else is truthy, including 0 and the empty string "", which surprises people coming from C, JavaScript or Python.

JS Truthiness and the and/or idiom (a JavaScript model)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

4. Explain a and b or c. When does it go wrong?

and returns its first operand if that is falsy, otherwise its second. or returns its first operand if that is truthy, otherwise its second. So cond and x or y acts like a ternary: x when cond is truthy, y otherwise. It breaks when x itself is falsy, because the or then falls through to y. The second line of the model above shows it: true and false or "no" gives "no". Use an if statement when the middle value can be nil or false. See Operators and Truthiness.

5. What is the difference between local and global variables?

A variable is global unless you declare it with local. A global is a field of the environment table (_ENV, which by default is _G), so assigning to an undeclared name silently creates a global, and a typo creates a new one instead of an error. Locals are lexically scoped to the block, are faster to access, and are the right default. Good habits: declare everything local, and put module functions in a local table. See Debugging, Performance and Common Mistakes.

6. Why does "10" + 5 work in Lua, and is that a good idea?

Lua coerces between strings and numbers in arithmetic: "10" + 5 is 15, and the concatenation 1 .. 2 is the string "12" (the spaces matter, because 1..2 is a malformed number). The coercion is convenient but hides bugs, so convert explicitly with tonumber and tostring when input comes from outside. tonumber("abc") returns nil, which you must check. See Numbers and the math Library.

7. What changed with integers in Lua 5.3 and 5.4?

Numbers can be 64-bit integers or double-precision floats. 7 // 2 is the integer 3, 7 / 2 is always a float (3.5), and 1 == 1.0 is true. Integer arithmetic wraps on overflow: math.maxinteger + 1 == math.mininteger. The // operator is floor division and % takes the sign of the divisor, so -7 // 2 is -4 and -7 % 3 is 2. LuaJIT and Lua 5.1 have only floats. See Numbers and the math Library.

Tables

8. Why is Lua called a "one data structure" language?

Arrays, dictionaries, sets, records, objects, modules and even the global environment are all tables. A table maps keys to values, and any value except nil (and NaN) can be a key. Syntax such as t.name is sugar for t["name"]. The runtime internally keeps a fast array part for sequential integer keys and a hash part for everything else, but your code does not choose between them. See Tables as Arrays and Dictionaries.

9. Why do Lua arrays start at 1?

It is a language convention: the first element of a sequence is t[1], and the length operator #t is also the index of the last element, so t[#t + 1] = v appends. The library (table.insert, ipairs, string.sub, string.find) follows the same convention, which is why ("hello"):sub(1, 1) is "h". Nothing stops you from using t[0], but it lives in the hash part and ipairs and # ignore it. Off-by-one errors when porting code from C or Python are the classic mistake.

10. What does #t return for a table with holes?

For a proper sequence (keys 1..n, no nil in between) it returns n. If the table has holes, #t may return any "border": an index n where t[n] is non-nil and t[n+1] is nil. Which border you get depends on the table's internal layout, so you cannot rely on it. The fix is to avoid holes, keep your own counter, or use table.pack/select("#", ...) when nil values matter.

11. What is the difference between pairs and ipairs?

ipairs(t) walks 1, 2, 3, ... in order and stops at the first nil. pairs(t) visits every key, in no guaranteed order. Use ipairs for sequences, pairs for dictionaries. You may assign nil to the field being visited during a pairs loop, but adding new keys during traversal is undefined behavior. See Iterating with pairs and ipairs.

JS ipairs stops at a hole, pairs does not (a JavaScript model)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

12. How do you copy a table?

Assignment copies the reference, so both names point at the same table. A shallow copy loops over pairs and writes each key into a new table; nested tables are still shared. A deep copy recurses and must handle cycles (keep a "seen" map) and decide what to do with metatables. See Tables in Practice.

LUA
local function shallow_copy(t)
  local copy = {}
  for k, v in pairs(t) do
    copy[k] = v
  end
  return copy
end

13. Is table.sort stable? What if my comparator is wrong?

No, it is not stable: equal elements may change their relative order. The comparator must be a strict "less than" (a < b, never a <= b). An inconsistent comparator can raise "invalid order function for sorting" or give wrong results. To sort by two keys, compare the first key, and fall back to the second only when the first are equal. See The table Library.

Functions and closures

14. Can a function return more than one value?

Yes. return a, b, c returns three values. A call used as the last item in a list expands to all its results, while in any other position (or when wrapped in parentheses) it is cut down to one. Missing values become nil and extra values are dropped. select("#", ...) counts arguments, including nils, and table.pack(...) collects them with a field n. See Functions and Varargs and Closures.

15. What is a closure, and what is an upvalue?

A closure is a function together with the local variables of enclosing scopes that it uses. Those captured variables are called upvalues. Each call to the enclosing function creates fresh variables, so two closures made by one factory do not share state, while two closures made in the same scope do share the variables they both capture. In a numeric or generic for loop each iteration gets a fresh loop variable, so closures created in the loop capture different values.

JS Closures with private state (a JavaScript model)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

16. What is a proper tail call?

When a function ends with return f(args) and nothing else, Lua reuses the current stack frame instead of adding a new one. Tail-recursive loops can therefore run forever without overflowing the stack. return 1 + f(x) and return (f(x)) are not tail calls. See Recursion and Tail Calls.

17. Why write local function fact(n) instead of local fact = function(n)?

With the second form the local variable fact is not yet in scope inside the function body, so a recursive call looks up a global fact, which is probably nil. local function f is sugar for local f; f = function ... end, so the name is visible inside.

Metatables and OOP

18. What is a metatable?

A metatable is an ordinary table attached to another table with setmetatable(t, mt). Its special fields, the metamethods (__index, __newindex, __add, __eq, __lt, __le, __call, __tostring, __len, __concat, __close, __gc and others), tell Lua what to do for operations the plain table does not support. getmetatable(t) reads it back, and a __metatable field can lock it. See Metatables and Metamethods.

19. How does __index work?

When you read a key that is absent from the table, Lua checks the metatable's __index. If it is a table, the lookup repeats there (and continues along that table's own metatable chain). If it is a function, Lua calls __index(t, key). This is the mechanism behind classes, inheritance and default values.

JS The __index chain (a JavaScript model)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

20. What is the difference between . and : when calling a function?

obj:method(x) is sugar for obj.method(obj, x): the table before the colon is passed as the first argument, conventionally named self. Defining function Class:method() ... end adds that hidden self parameter. Calling a colon-defined method with a dot and forgetting to pass the object is a very common bug. See Objects and Classes.

21. How do you implement a class and inheritance?

Put the methods in a table, set that table's __index to itself, and create instances with setmetatable({}, Class). A subclass is a new table whose metatable points __index at the parent. Calling the parent's method explicitly (Parent.method(self)) gives you a super call.

LUA
local Animal = {}
Animal.__index = Animal

function Animal.new(name)
  return setmetatable({ name = name }, Animal)
end

function Animal:speak()
  return self.name .. " makes a sound"
end

local Dog = setmetatable({}, { __index = Animal })
Dog.__index = Dog

function Dog.new(name)
  local self = Animal.new(name)
  return setmetatable(self, Dog)
end

function Dog:speak()
  return Animal.speak(self) .. ": Woof"
end

print(Dog.new("Rex"):speak())   --> Rex makes a sound: Woof

See Inheritance and Mixins.

22. How does == work on tables?

By default two tables are equal only if they are the same object. If both operands are tables (or both userdata), are not already rawequal, and have an __eq metamethod, Lua calls it and converts the result to a boolean. __lt and __le work similarly for < and <=. rawequal, rawget, rawset and rawlen bypass metamethods.

Coroutines, errors and modules

23. What is a coroutine?

A coroutine is a function with its own stack that can suspend itself with coroutine.yield and be continued with coroutine.resume. It is cooperative: nothing runs concurrently, and control moves only where you write resume and yield. Values passed to resume become the results of yield, and values passed to yield become the results of resume. Statuses are suspended, running, normal and dead. coroutine.wrap returns a function that resumes the coroutine and, unlike resume, rethrows errors. See Coroutines.

JS resume and yield passing values (a JavaScript generator model)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

24. How does error handling work?

error(value) raises any Lua value, usually a string or a table. pcall(f, ...) calls f in protected mode and returns true plus its results, or false plus the error value. xpcall(f, handler) calls a message handler at the point of the error, so debug.traceback can record the stack. assert(v, message) raises if v is falsy. Use tables as error values when callers need to distinguish error kinds. See Error Handling.

25. How do modules and require work?

A module is a file that builds a local table of functions and returns it. require("name") searches package.path, runs the file once, stores the returned value in package.loaded.name, and gives the same value on later calls. Returning a table, not defining globals, keeps modules independent. See Modules and require.

26. What do Lua patterns have in common with regular expressions, and what is missing?

Lua patterns have character classes (%d, %a, %s, %w), sets, quantifiers (*, +, -, ?), anchors, captures and back-references. They lack alternation (|), quantifiers on groups, and counted repeats such as {2,4}. Special characters are escaped with %, not a backslash. The extras are %b() for balanced pairs and %f[set] for frontiers. See String Patterns.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does print(nil == false) print in Lua?

    nil and false are both falsy but they are different values, so the comparison is false.
  2. 2. A table is {1, 2, nil, 4}. What does ipairs visit?

    ipairs walks 1, 2, 3, ... and stops at the first nil, so it sees keys 1 and 2 only.
  3. 3. What is obj:greet('hi') equivalent to?

    The colon passes the table before it as the first argument, conventionally named self.
  4. 4. Why can cond and x or y return the wrong value?

    When x is falsy, the and returns x, which makes or return y even though cond was true.
  5. 5. Which function runs code in protected mode and returns false plus an error value on failure?

    pcall catches errors and returns false and the error value. assert and error raise errors, and wrap rethrows them.

Summary

  • Only nil and false are falsy; 0 and "" are truthy.
  • Tables are the one structure behind arrays, records, objects and modules; sequences start at 1 and # is only reliable without holes.
  • Closures capture variables (upvalues); local function lets a function call itself.
  • Metatables supply behavior: __index drives classes and inheritance, and a:m() means a.m(a).
  • Coroutines are cooperative, errors are values handled with pcall, and require caches modules in package.loaded.

Next, keep this material within reach in the Lua Cheat Sheet.