Codectionary / Developer documentation / Lua

Lua string.gmatch token iteration

string.gmatch creates an iterator over successive pattern matches, extracting tokens without first allocating a complete token array.

Syntax

for token in text:gmatch("%S+") do ... end

Examples

Lua string.gmatch token iteration

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

local count = 0
for word in ("Lua   makes scripting useful"):gmatch("%S+") do
    count = count + 1
    print(count .. ":" .. word)
end
  1. Output: 1:Lua, 2:makes, 3:scripting and 4:useful on separate lines. %S+ selects runs of non-whitespace.

Best practices

  • Choose a pattern for the actual grammar. Whitespace tokenization does not parse quoted CSV or shell arguments.

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