Is my FizzBuzz code efficient?

Hello, I saw a video about fizzbuzz and decided to give it a go in Roblox. Here is my code:

local tests = {
	[3] = "Fizz",
	[5] = "Buzz"
}

for i = 1, 100, 1 do
	local output = ""
	for key, expectedOutput in pairs(tests) do
		if i%key == 0 then
			output = output..tests[key]
		end
	end
	if output == "" then
		print(i)
	else
		print(output)
	end
	
end

How is it?

Add some spacing to make this bit a little more readable.

you can shorten this to

output ..= tests[key]

Did not know that was an option. Thank you :smiley:

1 Like

I like your code, I have always had fun making efficient FizzBuzz scripts :slight_smile:

Using a pairs loop is expensive. It make it a little easier to add new tests, but it’s quite a cost.
I would recommend this style for speed:

for i = 1, 30 do
	local output = i .. ": "
	if i%3 == 0 then output ..= "Fizz" end
	if i%5 == 0 then output ..= "Buzz" end
	print(output)
end