Search code examples
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

    • If your function returns the whole animal_sounds table, though it is not what is asked of you, you get the animal sound by print(make_sound().cat):
      • make_sound is a function,
      • make_sound() returns a table,
      • make_sound()['cat'] is a field of that table,
      • and make_sound().cat is syntactic sugar for it, as is said in the answer above.
    • Also, better declare everything local, including function make_sound and animal_sounds table.
    • And you can skip [""]/[''] in table keys, if they are strings of basic Latin, numbers and underscores: cat = 'mew' not ['cat'] = 'mew'.
    • Unless you are going to use make_sound as a variable, it is better to declare it with local function syntax, rather than an assignment.
    • You can skip parentheses around the only string or table parametre in the function call: f'str' rather than f( 'str' ).
    • Most imporantly, your function never uses input, which is supposed to be the animal. Therefore, it has to return not the table, but the sound. So, move the [] part inside the function.

    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' )