World of Warcraft
Starcraft
Warcraft 3
Starcraft 2

PHP LUA Parsing Class

From Source Peek Wiki

Jump to: navigation, search

Credit goes to Freddy for this one (obviously because the codes not all tab indented :P)

array parseLUA(string abspath)

function parseLUA($filepath)
{
    $luaLinesArray = file($filepath);
$stack = array( array( "",  array()));
$stack_pos = 0;
$last_line = "";
foreach( $luaLinesArray as $line )
{
 if(substr( $line, -2, 1 ) == '\\')
 {
  $last_line .= substr($line, 0, -2) . "\n";
  continue;
 }
 $line = $last_line . $line;
 $last_line = "";
 if(strstr( $line, "=" ))
 {
  list($name, $value) = explode("=", $line, 2);
  $name = preg_replace( "/^\s*/","", $name);
  $name = preg_replace( "/\s*$/","", $name);
  if(substr($name,0,2) == "[\"")
  {
   $name = substr($name, 2, -2);
  }
  elseif(substr($name, 0, 1) == "[")
  {
   $name = intval(substr($name, 1, -1));
  }
  $name = trim($name, chr(0xEF).chr(0xBB).chr(0xBF));
  $value = preg_replace("/^\s*/", "", $value);
  $value = preg_replace("/\s*$/", "", $value);
  if($value == "{")
  {
   $stack_pos++;
   $stack[$stack_pos] = array($name, array());
  }
  else
  {
   if(preg_match("/^\"([^\"\\\\]|\\\\.)*\"/", $value, $matches))
   {
    $value = substr($matches[0],1,-1);
    $value = preg_replace( "/\\\\(.)/", "\\1", $value
    );
   }
   elseif(preg_match("/([0-9\.]*)e\+([0-9]+)/", $value, $matches))
   {
    #$value = $matches[1] * pow(10, $matches[2]);
    $value = floatval($matches[0]);
   }
   elseif(preg_match("/^-?[0-9]+\\.[0-9]+/", $value, $matches))
   {
    $value = floatval($matches[0]);
   }
   elseif(preg_match("/^-?[0-9+]+/", $value, $matches))
   {
    $value = intval($matches[0]);
   }
   elseif(preg_match("/^(True|False)/", $value, $matches))
   {
    if($matches[0] == "True")
    {
     $value = True;
    }
    else
    {
     $value = False;
    }
   }
   elseif(preg_match("/^nil/", $value))
   {
    $value = NULL;
   }
   $value = $value;
   $stack[$stack_pos][1][$name] = $value;
  }
 }
 elseif( preg_match("/^\s*}/", $line))
 {
  $hash = $stack[$stack_pos];
  $stack_pos--;
  $stack[$stack_pos][1][$hash[0]] = $hash[1];
 }
}
return $stack[0][1];
}
This page was last modified on 23 January 2007, at 00:50. This page has been accessed 3,423 times.