彼得标准库

lua-users home
wiki

这是我们目前项目中使用的标准库。它不是一个正式的提案,而是一个我们当前正在使用的库的快照。(参见:标准库提案

[!] 版本说明: 以下代码适用于旧版本的 Lua,Lua 4。它不能在 Lua 5 下直接运行。

它定义了以下函数。一些函数在单独的页面上列出

字符串函数:strcapitalize,strjoin,strsplit,sort(升级),findfile,readfile 和 writefile

表格函数 (PitLibTablestuff): tadd,tcopy,tdump,tfind

目录函数 (PitLibDirectoryStuff): dodirectory 和 fordirectory

字符串函数

-- 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

最近更改 · 偏好设置
编辑 · 历史记录
最后编辑于 2007 年 1 月 10 日 上午 5:39 GMT (差异)