让 Lua 像 PHP 一样 |
|
嗯... [为什么要那样做]? --f
注意:这些 PHP 风格的函数并不完全与 PHP 相同。在某些情况下,这是故意的。
请参阅 TableSerialization 中的 PHP 风格 print_r 函数。
示例:explode(" and ","one and two and three and four") --> {"one","two","three","four"}
兼容性:Lua 5.0、5.1、5.2 和(可能)5.3
function explode(div,str) -- credit: http://richard.warburton.it if (div=='') then return false end local pos,arr = 0,{} -- for each divider found for st,sp in function() return string.find(str,div,pos,true) end do table.insert(arr,string.sub(str,pos,st-1)) -- Attach chars left of current divider pos = sp + 1 -- Jump past current divider end table.insert(arr,string.sub(str,pos)) -- Attach chars right of last divider return arr end
使用 table.concat
PHP implode(join,array)
等效于 Lua table.concat(table,join)
PHP:implode(" ",array("this","is","a","test","array")) --> "this is a test array"
Lua:table.concat({"this","is","a","test","array"}," ") --> "this is a test array"
function phpTable(...) -- abuse to: http://richard.warburton.it local newTable,keys,values={},{},{} newTable.pairs=function(self) -- pairs iterator local count=0 return function() count=count+1 return keys[count],values[keys[count]] end end setmetatable(newTable,{ __newindex=function(self,key,value) if not self[key] then table.insert(keys,key) elseif value==nil then -- Handle item delete local count=1 while keys[count]~=key do count = count + 1 end table.remove(keys,count) end values[key]=value -- replace/create end, __index=function(self,key) return values[key] end }) for x=1,table.getn(arg) do for k,v in pairs(arg[x]) do newTable[k]=v end end return newTable end
示例用法
-- arguments optional test = phpTable({blue="blue"},{red="r"},{green="g"}) test['life']='bling' test['alpha']='blong' test['zeta']='blast' test['gamma']='blue' test['yak']='orange' test['zeta']=nil -- delete zeta for k,v in test:pairs() do print(k,v) end
输出
blue blue red r green g life bling alpha blong gamma blue yak orange
示例:preg_replace("\\((.*?)\\)","", " Obvious exits: n(closed) w(open) rift")
以下 preg_replace 变体支持在替换中使用通配符 *%n*。
1. 使用 Lua 风格的正则表达式
function preg_replace(pat,with,p) return (string.gsub(p,pat,with)) end
2. 使用 PCRE 或 POSIX 正则表达式
function preg_replace(pat,with,p) return (rex.gsub(p,pat,with)) end
[lua-phpserialize] 模块实现了将 Lua 表格序列化为 PHP serialize() 格式。