Improve error message when indexing string badly (with key not within the string library) #885

Merged
merged 1 commit into from Mar 31, 2015

Projects

None yet

3 participants

@willox
Collaborator
willox commented Mar 4, 2015

The current error message is very difficult for new (and old) developers to understand and also doesn't resemble any error messages in stock Lua.

local str = "Hello!"; print( str:sab( 1, 5 ) )

--[[
    New Error: [ERROR] lua_run:1: attempt to index a string value with bad key ('sab' is not part of the string library)
    Old Error: [ERROR] lua_run:1: bad key to string index (number expected, got string)
]]

I'd almost be in favour of following the way stock Lua handles this and returning nil, but it'd a better idea to stick to current functionality of gmod.

@willox willox Improve error message when indexing string badly
The current error message is very difficult for new (and old) developers
to understand and also doesn't resemble and error messages in stock Lua.
d972a67
@Bo98 Bo98 referenced this pull request in Facepunch/garrysmod-issues Mar 6, 2015
Closed

IsValid errors for boolean, numbers, strings #1828

@robotboy655 robotboy655 merged commit 079bbe1 into garrynewman:master Mar 31, 2015
@willox willox deleted the unknown repository branch Mar 31, 2015
@AshleighAdams
Contributor

I'd almost be in favour of following the way stock Lua handles this and returning nil, but it'd a better idea to stick to current functionality of gmod.

I do wonder if this would be better.

Changing the definition to:

function meta:__index( key )
    local val = string[ key ]
    if ( val ) then
        return val
    elseif ( tonumber( key ) ) then
        return self:sub( key, key )
    else
        return nil
    end
end

The example error message would now become:

attempt to call method 'sab' (a nil value)

As a side-effect the following code now also works as expected (will crash under gmod, but not typical Lua):

local x = "asd"
if x.field then
    print("does exist")
else
    print("does not exist")
end

Currently, this will crash with:

attempt to index a string value with bad key ('field' is not part of the string library)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment