How to use text as a seed in math.noise?

I’m working on a terrain generator, that uses 3D Perlin noise to generate terrain:

And since it uses Perlin noise, it also uses a seed, and seed is typically a number. Now, in games like BLOX / minecraft, you’re able to use text as a seed.

But if I use text as a seed in my terrain generator, I get an error. Is there any way I can use text as a seed in math.noise?

1 Like

I think Minecraft uses hashCode() to accomplish this. It becomes integers I am guessing to get that seed result. Source: Google & that hyperlink

2 Likes

Is there any way to do a “hashcode” in lua?

1 Like

I am unfamiliar unfortunately with hashcode algorithms but you could probably experiment with string.byte for a different approach.

2 Likes

Is there any resources you know of, so I can learn more about it?

1 Like

Try assigning each character a number, or use the ascii value of the characters.

2 Likes

You could hash the string with md5 or something, but that’s probably overkill for what you want. Something really simple might be better. e.g. using string.byte:

local function StringToNumber(str)
	local val = 0

	for i = 1, str:len() do
		val = val + str:byte(i)
	end

	return val
end

This is a terrible hashing function and will return the same thing for e.g. abc and bca, but it’s up to you if you care that much.

edit: here, on the other end of the spectrum, is an implementation of sha1 hashing in lua.

2 Likes

Its not that bad, because it turns the letters to numbers:

Screenshot (310)

Ima accept this as the solution for now, but if someone has something better, then please post it here!

Thanks for your help @nicemike40!

EDIT:

I’m actually going to use this script:

local function StringToNumber(str)
	local num = ""
	for i = 1, str:len() do
		num = num..str:byte(i)
	end

	return tonumber(num)
end

Either way, thanks! :>

1 Like

More info: according to this, minecraft uses the java String.hashCode() function to convert the strings to numbers.

Apparently, that’s calculated like this:

s[0]*31^(n - 1) + s[1]*31^(n - 2) + ... + s[n - 1]

Which in lua would be:

local max32 = math.pow(2, 32) - 1

local function HashCode(str)
	local val = 0

	local n = str:len()

	for i = 1, n do
		val = (val + str:byte(i) * math.pow(31, n - i)) % max32
	end

	return val
end
6 Likes