讓Lua像Php

lua-users home
wiki

這裡有一些函式或程式碼片段可以讓Lua行為更像PHP。

呃... [你為什麼會想要那樣]?——F

注意:這些PHP風格函式中有些和PHP的作法不完全相同。在某些情況下這是故意的。

print_r

請參閱TableSerialization中的類似PHP的print_r函式。

explode

基於[PHP explode]

範例: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

implode

基於[PHP implode]

使用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"

PHP表格

PHP陣列保留鍵值對的加入順序。Lua默認情況下並非如此。但這種功能可以被複製。

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

基於[PHP preg_replace]

範例: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

Nutria

[Nutria]是用Lua撰寫的PHP標準函式庫。

serialize()

[lua-phpserialize]模組將Lua表格序列化為PHP serialize()格式。

另請參閱


RecentChanges · 偏好
編輯 · 歷史
最後編輯時間為2018年6月20日下午1時49分格林威治時間(diff)