lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Here is the Lua string library (lstrlib.c) partially reimplemented in
Lua (mainly, string.find and string.match functions):

  http://lua-users.org/wiki/StringLibraryInLua

Reimplementing these in Lua provides a number of generalizations and
possible applications:

  * The pattern matching library can be extended in Lua

  * The pattern matching can match not just strings but more generally
arrays of chars and arrays of arbitrary values, including arrays
backed by metamethods.  The filearray.lua example included in the
appendix allows a large file to be accessed via an array interface,
which can then be matched by these string.find/string.match functions,
without ever loading the entire file into memory at once:

  local S = require "stringinlua"  -- reimplemented pattern matching functions
  local FA = require "filearray"   -- table array interface to files
  local SA = require "stringarray" -- table array interface to simple strings

  -- match text in file manual.html (internally, only a 1K is loaded at a time)
  assert(S.match(assert(FA 'manual.html'), SA'block ::= (%w+)') == 'chunk')

Another example, of using this to match arrays that are not char
strings is this:

  local TA = require "tablearray" -- table array interface to tables

  -- match value false followed by one or more occurrences of value 'test'
  assert(S.match(TA{2,false,"test","test",2}, TA{false,"test", '+'})
            == TA{false,"test", "test"})

Unicode matching may be another application (i.e. arrays of Unicode characters).