lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Walter Rodrigo de Sá Cruz wrote:
Hey guys! I get in this list today :)

In PHP, I can make this with preg:


preg_match('/^(\/var\/www\/)(.*)/', '/var/www/files/index.php', $array_result);

and I will get:
$array_result[0] = /var/www/files/index.php
$array_result[1] = /var/www/
$array_result[2] = files/index.php

How can I get a similar thing in Lua ?


array_result = { string.find('/var/www/files/index.php', '^(/var/www/)(.*)') }

The differences:

- Lua's array/list/table starts at index 1, and not 0.
- string.find returns where the match begins and end, so, array_result[1] is equal to 1, array_result[2], in this case, is equal to 24, array_result[3] is the first match ("/var/www/") and array_result[4], the second match: "files/index.php" - To use it as array (list/table), you need to enclose the call into brackets: "{" and "}", but usually you would, instead:

local s,e,path,file = string.find('/var/www/files/index.php', '^(/var/www/)(.*)')

Note1: It is much more cheap to return multiple values than create a table
Note2: Most prefer to name the locals as: "local _,_,path,file = ..."
Note3: In the not-yet-released Lua 5.1, you could use the built-in function "select" to skip those unnecessary values: "local path,file = select(3,string.find(....)))"


Hope it helps :)

--rb