Codectionary / Developer documentation / Lua

Lua literal substring searches

string.find normally treats its needle as a pattern. Its fourth argument selects literal searching, useful for punctuation or user-supplied search text.

Syntax

local first, last = string.find(text, needle, 1, true)

Examples

Lua literal substring searches

Run with standalone Lua 5.4: lua example.lua. These scripts target Lua 5.4 rather than Roblox Luau.

local text = "report.final.csv"
local first, last = string.find(text, ".", 1, true)
if first then
    print(first, last)
    print(text:sub(1, first - 1))
end
  1. Output: 7 and 7 on the first line, then report. A dot in pattern mode would match any character.

Best practices

  • Check the nil result before using positions. String offsets count bytes, including in UTF-8 text.

Runtime & versions

Lua interpreter or a host application. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Lua reference manuals

Specifications & further reading