讓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()格式。