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.
This commit is contained in:
Ian Farmer
2008-06-02 04:14:13 +00:00
parent db457117e3
commit 807541ace2
2 changed files with 10 additions and 5 deletions

View File

@@ -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;
}

View File

@@ -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 {