lua

Lua How to create a table inside a function?


I'm a beginner at Lua and programming in general (I've had some experience in other languages but nothing huge) and I've been following a tutorial where there's this one exercise on tables:

"Make a function with a table in it, where each key in the table is an animal name. Give each key a value equal to the sound the animal makes and return the animal sound. Try invoking the function and see if you get back the correct sound."

Here's my current solution:

make_sound = function(input)
  animal_sounds = {
    ["cat"] = "meow",
    ["dog"] = "woof"
  }

return animal_sounds.input

end

  print(make_sound("cat"))

This just prints 'nil'. I've tried so many variations of this but they all either print 'nil' as well or give me an error saying something about nil (sorry I can't remember the original message or erroneous code).

I know this is a really dumb question and probably has an extremely basic answer so I'm sorry for my stupidity. All the other exercises have been a breeze and then I suddenly get hit with this thing for an hour. I searched everywhere but could only find results about functions inside arrays or something else completely. I didn't want to just give up on a seemingly easy task so here I am...


Solution

  • So:

    local function make_sound( input )
        local animal_sounds = {
            cat = 'meow',
            dog = 'woof',
            cow = 'moo'
        }
        return animal_sounds[input]
    end
    
    print( make_sound 'cat' )
    

    P.S. You can even make the table anonymous, though it will need to be surrounded with parentheses, otherwise Lua will think that return is not the last operator before end as it should be:

    local function make_sound( input )
        return ({
            cat = 'meow',
            dog = 'woof',
            cow = 'moo'
        })[input]
    end
    
    print( make_sound 'cat' )