From 807541ace2ff69b486879cdd1fc34391fd389c46 Mon Sep 17 00:00:00 2001 From: Ian Farmer Date: Mon, 2 Jun 2008 04:14:13 +0000 Subject: [PATCH] Fix table.remove: (1) When nothing is removed, it returns zero results, not 1 nil result. (2) Ignore requests to remove elements past the length of the table. --- src/core/org/luaj/lib/TableLib.java | 8 +++++--- src/core/org/luaj/vm/LTable.java | 7 +++++-- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/src/core/org/luaj/lib/TableLib.java b/src/core/org/luaj/lib/TableLib.java index f2518354..b502cd67 100644 --- a/src/core/org/luaj/lib/TableLib.java +++ b/src/core/org/luaj/lib/TableLib.java @@ -22,9 +22,9 @@ package org.luaj.lib; import java.io.ByteArrayOutputStream; -import java.io.IOException; import org.luaj.vm.LFunction; +import org.luaj.vm.LNil; import org.luaj.vm.LString; import org.luaj.vm.LTable; import org.luaj.vm.LValue; @@ -171,12 +171,14 @@ public class TableLib extends LFunction { * Returns the value of the removed element. The default value for pos is n, where n is the length of the table, * so that a call table.remove(t) removes the last element of table t. */ - case REMOVE: { + case REMOVE: { int n = vm.gettop(); LTable table = vm.totable(2); int pos = (n>=3? vm.tointeger(3): 0); vm.resettop(); - vm.pushlvalue( table.luaRemovePos(pos) ); + LValue removed = table.luaRemovePos( pos ); + if ( removed != LNil.NIL ) + vm.pushlvalue( removed ); break; } diff --git a/src/core/org/luaj/vm/LTable.java b/src/core/org/luaj/vm/LTable.java index f6698d6b..5d275fe3 100644 --- a/src/core/org/luaj/vm/LTable.java +++ b/src/core/org/luaj/vm/LTable.java @@ -343,9 +343,12 @@ public class LTable extends LValue { * @param pos position to remove, or 0 to remove last element */ public LValue luaRemovePos(int ikey) { + int n = luaLength(); if ( ikey == 0 ) - if ( (ikey = luaLength()) <= 0 ) - return LNil.NIL; + ikey = n; + if ( ikey <= 0 || ikey > n ) + return LNil.NIL; + LValue removed = get(ikey); LValue replaced; do {