Chuyển đến nội dung

Bài 28 · Neovim and Lua

Lua for Neovim Users

Learn the part of Lua you need for Neovim: variables, tables, functions, loops, modules with require, pcall and the gotchas that trip up newcomers, with runnable JS stand-ins.

Lua is a small, fast scripting language. Neovim embeds it (LuaJIT, a Lua 5.1 compatible runtime), so your configuration can call the editor directly. You do not need to master Lua to configure Neovim, but a handful of ideas appear in every config. This lesson teaches those.

The site has no Lua runner, so the Lua code below is read-only. Where it prints something obvious, the output is shown; the interactive blocks are JavaScript stand-ins that mirror a Lua rule so you can experiment with it.

Values and variables

LUA
local name = "Ada"        -- strings: single or double quotes
local count = 3           -- numbers
local active = true       -- booleans
local nothing = nil       -- the absence of a value
print(name .. " has " .. count)   --> Ada has 3

Key points:

  • Always write local. A variable without it becomes global, which is a common source of bugs.
  • Comments start with --; block comments use --[[ ... ]].
  • String concatenation is .., not +.
  • Only nil and false are falsy. 0 and the empty string are truthy, unlike many languages.
  • Not-equal is ~=; logic uses and, or, not.
  • There are no ++ or += operators: write count = count + 1.

Tables: the only data structure

A table is both array and dictionary.

LUA
local fruits = { "apple", "pear", "plum" }
print(fruits[1])           --> apple     (indexes start at 1!)
print(#fruits)             --> 3

local user = { name = "Ada", age = 36 }
print(user.name)           --> Ada
user.email = "[email protected]"

local mixed = { "a", "b", key = "value" }

Arrays start at 1. #t is the length of an array part. Use table.insert(fruits, "fig") to append and table.remove(fruits, 1) to remove. Neovim's configuration is mostly tables: options, plugin specs and keymap arguments are all tables.

JS Stand-in: Lua's 1-based indexing and truthiness

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

No output.

Control flow and loops

LUA
if count > 5 then
  print("big")
elseif count == 3 then
  print("three")
else
  print("small")
end

for i = 1, 3 do print(i) end            --> 1 2 3
for i, v in ipairs(fruits) do print(i, v) end
for key, value in pairs(user) do print(key, value) end
while count > 0 do count = count - 1 end

ipairs walks an array in order; pairs visits every key (order is not guaranteed). Blocks end with end, not braces.

Functions

LUA
local function greet(name)
  return "Hello, " .. name
end

local add = function(a, b) return a + b end

vim.keymap.set("n", "<leader>g", function()
  print(greet("Neovim"))
end)

Functions are values, so you can pass them as callbacks, as in the keymap above. A call with one table or string argument can omit the parentheses: require "config" and vim.cmd [[ set number ]]. Calling obj:method(x) is shorthand for obj.method(obj, x); Neovim uses it for objects like vim.opt.listchars:append(...).

Modules and require

A Lua file returns a table, and other files load it with require.

LUA
-- ~/.config/nvim/lua/config/options.lua
local M = {}
function M.setup()
  vim.opt.number = true
end
return M
LUA
-- init.lua
require("config.options").setup()

require("config.options") looks in the lua/ folders of the runtimepath for config/options.lua (or config/options/init.lua). Dots stand for folders. The result is cached: the file runs once, and later calls return the same table. To reload during development, clear package.loaded["config.options"].

JS Stand-in: require caches the module

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

No output.

Handling errors with pcall

A failing require stops your whole config. pcall (protected call) catches the error:

LUA
local ok, plugin = pcall(require, "telescope")
if not ok then
  vim.notify("telescope is not installed", vim.log.levels.WARN)
  return
end
plugin.setup({})

pcall(f, ...) returns true plus the results, or false plus the error message. Use it for optional plugins so a missing one does not break startup.

Strings and useful helpers

  • string.format("%d lines", n) or ("%s-%s"):format(a, b) builds strings.
  • #s is the byte length; s:sub(1, 3), s:upper(), s:find("x", 1, true) for plain text, s:gsub("a", "b").
  • Lua patterns are not regular expressions. They use % as the escape: %d digit, %s space, %w alphanumeric, . any, - lazy. Use vim.regex or vim.fn.matchstr if you need Vim regex.
  • vim.inspect(tbl) turns any value into readable text; vim.print(tbl) prints it. This is the debugging tool you will use most.
  • vim.tbl_extend("force", a, b) merges tables; vim.tbl_deep_extend merges nested ones; vim.list_extend appends a list; vim.tbl_keys, vim.tbl_contains, vim.split, vim.trim.

Gotchas

  1. Arrays start at 1; t[0] is nil.
  2. Forgetting local makes a global.
  3. 0 is true; only nil and false are false.
  4. # on tables with holes is unreliable.
  5. == on tables compares identity, not contents.
  6. Method calls use : and field access uses .; mixing them gives "attempt to index a nil value".
  7. Vim functions return 0/1 for booleans (vim.fn.has("win32") == 1), not Lua booleans. vim.fn.has is the exception worth remembering.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What is the first element of the Lua table t = { 'a', 'b' }?

    Lua arrays are 1-based. t[0] is nil.
  2. 2. Which values are falsy in Lua?

    Only nil and false are falsy. 0 and the empty string are truthy.
  3. 3. What does pcall(require, 'plugin') do?

    pcall runs the function in protected mode and returns a success flag, so optional plugins cannot break startup.
  4. 4. How do you load lua/config/options.lua from init.lua?

    Dots map to folders under a lua/ directory on the runtimepath, and the result is cached.

Summary

  • Always use local; strings join with ..; only nil and false are falsy.
  • Tables are arrays (1-based) and dictionaries; config is mostly tables.
  • Functions are values; use them as callbacks in keymaps and autocommands.
  • require("a.b") loads lua/a/b.lua once; pcall protects optional modules.
  • vim.inspect and vim.print are your debuggers.

Next: Writing init.lua

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.