Balanced provides functions for matching delimited snippets of Lua code in a string.
Home page: http://lua-users.org/wiki/LuaBalanced (this page)
This module can, for example, match a Lua string, Lua comment, or Lua expression. It is useful in particular for source filters or parsing Lua snippets embedded in another language. It is inspired by Damian Conway's Text::Balanced  in Perl. The unique feature of this implementation is that that it does not rigorously lex and parse the Lua grammar. It doesn't need to. It assumes during the parse that the Lua code is syntactically correct (which can be verified later using
loadstring). By assuming this, extraction of delimited sequences is significantly simplified yet can still be robust, and it also supports supersets of the Lua grammar. The code, which is written entirely in Lua, is just under 200 lines of Lua code (compare to Yueliang used in MetaLua, where the lexer alone is a few hundred lines).
Projects using this module: ListComprehensions
local lb = require "luabalanced" -- Extract Lua expression starting at position 4. print(lb.match_expression("if x^2 + x > 5 then print(x) end", 4)) --> x^2 + x > 5 16 -- Extract Lua string starting at (default) position 1. print(lb.match_string([["test\"123" .. "more"]])) --> "test\"123" 12 -- Break Lua code into code types. lb.gsub([[ local x = 1 -- test print("x=", x) ]], function(u, s) print(u .. '[' .. s .. ']') end) --[[output: e[ local x = 1 ] c[-- test ] e[ print(] s["x="] e[, x) ] ]]
Downloadable from [github].
This module is new and likely still has some bugs.