Skip to content

Instantly share code, notes, and snippets.

@scheler
Created July 23, 2020 00:17
Show Gist options
  • Save scheler/26a942d34fb5576a68c111b05ac3fabe to your computer and use it in GitHub Desktop.
Save scheler/26a942d34fb5576a68c111b05ac3fabe to your computer and use it in GitHub Desktop.
String hash function in Lua
function hash(str)
h = 5381;
for c in str:gmatch"." do
h = ((h << 5) + h) + string.byte(c)
end
return h
end
@karelbilek
Copy link

Also, this will work with older lua versions without << and will not use gmatch

function hash(str)
    local h = 5381

    for i = 1, #str do
       h = h*32 + h + str:byte(i)
    end
    return h
end

@karelbilek
Copy link

(I am not sure if the h*32 + h or h<<5 + h is really faster than just h*33 )

@jarom-nelson
Copy link

jarom-nelson commented Oct 10, 2024

You'll want to mod by 2^31 to keep it within 32 bits or you'll get a double floating point number eventually.

function hash(str)
    h = 5381;

    for c in str:gmatch"." do
        h = math.fmod(((h << 5) + h) + string.byte(c), 2147483648)
    end
    return h
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment