Give LValue an add() method, to eventually respect metamethods

Fri, 19 Nov 2010 13:09:25 +0000

author
Matthew Wild <mwild1@gmail.com>
date
Fri, 19 Nov 2010 13:09:25 +0000
changeset 72
dc73a60b3c06
parent 71
768d8fb574bb
child 73
6b43d68abc94

Give LValue an add() method, to eventually respect metamethods

lvm.js file | annotate | diff | comparison | revisions
--- a/lvm.js	Fri Nov 19 04:05:19 2010 +0000
+++ b/lvm.js	Fri Nov 19 13:09:25 2010 +0000
@@ -99,6 +99,26 @@
 		default:
 			return this.value.toString();
 		}
+	},
+	add: function (op2)
+	{
+		var metamethod;
+		var __add = LValueFromString("__add");
+		if(this.metatable)
+			metamethod = this.metatable.index(__add);
+		if((!metamethod || metamethod.type == "nil") && op2.metatable)
+			metamethod = op2.metatable.index(__add);
+		if(metamethod && metamethod.type != "nil")
+		{
+		}
+		else if((this.type == "number" || this.type == "string")
+			&& (op2.type == "number" || op2.type == "string"))
+		{
+			// Plain addition
+			return new LValue("number", parseFloat(this.value, 10) + parseFloat(op2.value));
+		}
+		else
+			throw "Attempt to perform arithmetic on a "+this.type+" and "+op2.type;
 	}
 };
 
@@ -518,7 +538,7 @@
 			case OP_ADD:
 				var RB = frame.reg[INS_B(instruction)];
 				var RC = frame.reg[INS_C(instruction)];
-				frame.reg[INS_A(instruction)] = new LValue("number", RB.value + RC.value);
+				frame.reg[INS_A(instruction)] = RB.add(RC);
 				break;
 			case OP_SUB:
 				var RB = frame.reg[INS_B(instruction)];

mercurial