Menu

#55 Wrong type when changing a number variable into a string (includes fix)

v3.0.1
open
nobody
None
5
2018-10-30
2018-10-30
No

When running the following Lua code in LuaJ, the type of the variable a doesn't change to string, but remains a number. This cause an unexpected behaviour when assigning strings that looks like numbers to a variable that was of type number. This doesn't happen when variables are first initialized to string type, like b in the example below.

a = 10 
print(type(a)) -- number
print(a) -- 10

b = "10.00" 
print(type(b)) -- string
print(b) -- 10.00

a = "10.00" 
print(type(a)) -- number, expected string!
print(a) -- 10, expected 10.00

On other Lua interpreters, the code runs as expected. I think that problem arises in the class NumberValueEntry in LuaTable.java, in particular in the method that is called when the entry needs to be changed:

public Entry set(LuaValue value) {
    LuaValue n = value.tonumber();
    if ( !n.isnil() ) {
        this.value = n.todouble();
        return this;
    } else {
        return new NormalEntry( this.key, value );
    }
}

Here you can see that if the new value can be coerced to a number, the entry is updated just by changing its double value to the new value, converted to double. If the new value is not number-like, a new entry is returned. This is incorrect. I don't get why there's the need to have a NumberValueEntry in the first place, but instead of removing it altogether, it could be fixed keeping the entry-reusing login by checking the new value type instead of trying to coerce it to a number. The change below fixes the example above:

public Entry set(LuaValue value) {
    if (value.type() == TNUMBER) {
        LuaValue n = value.tonumber();
        if (!n.isnil()) {
            this.value = n.todouble();
            return this;
        }
    }
    return new NormalEntry( this.key, value );
}

Discussion


Log in to post a comment.