彼得标准库 |
|
[!] 版本说明: 以下代码适用于旧版本的 Lua,Lua 4。它不能在 Lua 5 下直接运行。
它定义了以下函数。一些函数在单独的页面上列出
-- 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