Use what the user type (io.read) as a function argument in Lua

Asked

Viewed 56 times

1

I have the following function:

function perfil(monstro)
    print(monstros.monstro.nomeM)
    print(monstros.monstro.racaM)
    print(monstros.monstro.generoM)
    print(monstros.monstro.idadeM)
    print(monstros.monstro.descM)
end

And this table:

monstros = {
    Esqueleto = {nomeM = "Skeletran", racaM = "Esqueleto", generoM = "F", idadeM = "455", descM = "'Estou morta mas não o suficiente!'"},
    Zumbi = {nomeM = "Bruce Santos", racaM = "Zumbi", generoM = "M", idadeM = "19", descM = "'Prociza ter umh celbro de 17 centismotros       .'"},
    Sirena = {nomeM = "Alamellia", racaM = "Sirena", generoM = "F", idadeM = "18", descM = "'Minhas canções são as melhores! Inspirante á Cantora :-D'"},
    Ogro = {nomeM = "Crak", racaM = "Ogro", generoM = "M", idadeM = "34", descM = "'hngbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbyæ'"},
    Dragoa = {nomeM = "SUZANA", racaM = "DRAGÂO", generoM = "F", idadeM = "1367", descM = "'GOOSTO DE FLORESS VERMELHHAS'"}
}

I want to make the user use io.read to change the parameter monstro in function perfil. If there is any other error in my code, let me know! (I am aware that I need to use that to use accentuation)

1 answer

1

To access a property dynamically, you must use brackets:

function perfil(monstro)
    print(monstros[monstro].nomeM)
    print(monstros[monstro].racaM)
    print(monstros[monstro].generoM)
    print(monstros[monstro].idadeM)
    print(monstros[monstro].descM)
end

After that just read the user input and call the function:

local resposta = io.read()
perfil(resposta)

See working on Ideone.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.