HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

print(fizz..buzz)

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
buzzfizzprint

Problem

I couldn't help but notice we didn't have a FizzBuzz in lua yet.
I've always wanted to take a shot at Lua, so here goes nothing.

Code:

function fizzBuzz(maxNum)
local fizz = "Lua"
local buzz = "Yay"
for i = 1, maxNum do
if i % 15 == 0 then
print(fizz..buzz)
elseif i % 3 == 0 then
print(fizz)
elseif i % 5 == 0 then
print (buzz)
else
print(i)
end
end
end

fizzBuzz(100)


Output:

1
2
Lua
4
Yay
Lua
7
8
Lua
Yay
11
Lua
13
14
LuaYay
16
17


I highly doubt it's idiomatic Lua, so I'm open for suggestions. As far as I know mixedCase and 2-space indentation are the way to go for Lua, but feel free to prove me wrong.

Solution

Lua, by definition is an embeddable scripting language. So, there are no guidelines as to how you want to create a variable or indent your code. It largely is a factor of how a developer feels comfortable.

Please note that although there is a style guide available for Lua, it actually is an amalgamation of Python, Perl, C and C++ style guides.

Two things, which I have seen common among a lot of lua programs/modules is that the function names (if not defined as a method of an object) are defined in snake_case, and if defined as a method to an object, use CamelCase (with both C capitalised). And another is, the variables for general data-types (number, string, function, table, boolean) follow a Hungarian notation.

In your fizzbuzz, when calling the print function, you have given an extra space for the buzz output, whereas nothing as such for others. Keeping it consistent:

if i % 15 == 0 then
  print(fizz..buzz)
elseif i % 3 == 0 then
  print(fizz)
elseif i % 5 == 0 then
  print(buzz)    -- remove whitespace
else
  print(i)
end


You could also store the fizz..buzz value outside of the loop, just to avoid one extra calculation. Apart from that everything looks good.

Code Snippets

if i % 15 == 0 then
  print(fizz..buzz)
elseif i % 3 == 0 then
  print(fizz)
elseif i % 5 == 0 then
  print(buzz)    -- remove whitespace
else
  print(i)
end

Context

StackExchange Code Review Q#139078, answer score: 4

Revisions (0)

No revisions yet.