Peters Std Lib

lua-users home
wiki

This is the standard library that we use for our project so far. It's not really a proposal but rather a snapshot of what we are using currently. (see also: StandardLibraryProposal)

[!] VersionNotice: The below code pertains to an older Lua version, Lua 4. It does not run as is under Lua 5.

It defines these functions. Some are listed on separate pages:

String functions: strcapitalize, strjoin, strsplit, sort (upgrade), findfile, readfile and writefile:

Table functions (PitLibTablestuff): tadd, tcopy, tdump, tfind

Directory functions (PitLibDirectoryStuff): dodirectory and fordirectory

String functions

-- like strupper applied only to the first character

function strcapitalize(str)

  return strupper(strsub(str, 1, 1)) .. strlower(strsub(str, 2))

end



-- Concat the contents of the parameter list,

-- separated by the string delimiter (just like in perl)

-- example: strjoin(", ", {"Anna", "Bob", "Charlie", "Dolores"})

function strjoin(delimiter, list)

  local len = getn(list)

  if len == 0 then return "" end

  local string = list[1]

  for i = 2, len do string = string .. delimiter .. list[i] end

  return string

end



-- Split text into a list consisting of the strings in text,

-- separated by strings matching delimiter (which may be a pattern). 

-- example: strsplit(",%s*", "Anna, Bob, Charlie,Dolores")

function strsplit(delimiter, text)

  local list = {}

  local pos = 1

  if strfind("", delimiter, 1) then -- this would result in endless loops

    error("delimiter matches empty string!")

  end

  while 1 do

    local first, last = strfind(text, delimiter, pos)

    if first then -- found?

      tinsert(list, strsub(text, pos, first-1))

      pos = last+1

    else

      tinsert(list, strsub(text, pos))

      break

    end

  end

  return list

end



-- a better standard compare function for sort

local standard_cmp = function(a,b) 

  if type(a) == type(b) then 

    return a < b 

  end 

  return type(a) < type(b) 

end



-- upgrade sort function 

-- (default compare function now accepts different types in table)

function sort(table, f_cmp)

  return %sort(table, f_cmp or %standard_cmp)

end



-- check if a file exists, returns nil if not

function findfile(name)

  local f = openfile(name, "r")

  if f then

    closefile(f)

    return 1

  end

  return nil

end



-- read entire file and return as string

function readfile(name)

  local f = openfile(name, "rt")

  local s = read(f, "*a")

  closefile(f)

  return s

end



-- write string to a file

function writefile(name, content)

  local f = openfile(name, "wt")

  write(f, content)

  closefile(f)

end


RecentChanges · preferences
edit · history
Last edited January 10, 2007 4:39 am GMT (diff)