Skip to content

Commit 6e117ff

Browse files
committed
Add support for negative numbers, fixes #6
1 parent 70495bf commit 6e117ff

File tree

3 files changed

+44
-1
lines changed

3 files changed

+44
-1
lines changed

src/TokenStream.php

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,9 @@ protected function readNext() {
9191
if ($this->isDigit($char)) {
9292
return $this->readNumber();
9393
}
94+
if ($char === '-') {
95+
return $this->readNumber();
96+
}
9497
if ($this->isStartIdentifierCharacter($char)) {
9598
return $this->readIdentifier();
9699
}
@@ -233,6 +236,23 @@ protected function readEscaped($end) {
233236
* @return Token
234237
*/
235238
protected function readNumber() {
239+
$isNegative = false;
240+
241+
if ($this->input->peek() === '-') {
242+
$isNegative = true;
243+
$this->input->next();
244+
}
245+
246+
$number = $this->readNumberValue();
247+
248+
if ($isNegative) {
249+
$number *= -1;
250+
}
251+
252+
return new Token(Token::TYPE_NUMBER, $number);
253+
}
254+
255+
private function readNumberValue() {
236256
$hasDot = false;
237257
$number = $this->readWhile(
238258
function ($char) use (&$hasDot) {
@@ -246,7 +266,8 @@ function ($char) use (&$hasDot) {
246266
return $this->isDigit($char);
247267
}
248268
);
249-
return new Token(Token::TYPE_NUMBER, $hasDot ? floatval($number) : intval($number));
269+
270+
return $hasDot ? floatval($number) : intval($number);
250271
}
251272

252273
/**

tests/LuaToPhpConverterTest.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,4 +111,18 @@ public function testAdvancedTable() {
111111
count($result)
112112
);
113113
}
114+
115+
// https://github.com/koesie10/LuaSerializer/issues/6
116+
public function testNegativeNumberTable() {
117+
$parser = new Parser(new TokenStream(new InputStream('{1.75,0.6,-1.78}')));
118+
119+
$node = $parser->parse();
120+
121+
$result = LuaToPhpConverter::convertToPhpValue($node);
122+
123+
$this->assertEquals(
124+
[1.75, 0.6, -1.78,],
125+
$result
126+
);
127+
}
114128
}

tests/LuaTokenStreamTest.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,14 @@ public function testNumberFloat() {
8787
$this->assertEquals(13.37, $token->getValue());
8888
}
8989

90+
public function testNumberNegative() {
91+
$obj = new TokenStream(new InputStream("-13.37"));
92+
93+
$token = $obj->next();
94+
$this->assertEquals(Token::TYPE_NUMBER, $token->getType());
95+
$this->assertEquals(-13.37, $token->getValue());
96+
}
97+
9098
public function testPunctuation() {
9199
foreach ([',', '{', '}', '=', '[', ']'] as $punc) {
92100
$obj = new TokenStream(new InputStream($punc));

0 commit comments

Comments
 (0)