1

I am trying to do a simple program in lua that aims to return a string with certain values based on the user input, however I am having issues scripting this.

For example, if I compile

person1 = {
name = "bob" ,
age = 70 ,
hair = "black" ,
};
person2 = {
name = "dan",
age = 40 ,
hair = "blonde" , 
};
describe = function(parent)
print ( "hello " .. parent.name .. " your are " .. parent.age .. " years old
and your hair color is " .. parent.hair )
end
print ("who are you") ;
answer = io.read ();
describe (answer) 

I would expect that if I wrote person1 as the input the script would return a string that reads:

hello bob you are 70 years old and your hair color is black

However it instead returns an error.

The question is, what can I do to fix this? What is the right way to use user input in Lua?

1
  • 1
    You should indent your code, it makes it easier to read for us. Commented Aug 7, 2016 at 8:35

1 Answer 1

1

You would have to pass the object to the function, not the name. Or search for the object in the global scope:

person1 = {
    name = "bob" ,
    age = 70 ,
    hair = "black" ,
};
person2 = {
    name = "dan",
    age = 40 ,
    hair = "blonde" , 
};
describe = function(parent)
    parent = _G[parent]
    print ( "hello " .. parent.name .. " your are " .. parent.age .. " years old and your hair color is " .. parent.hair )
end
print ("who are you") ;
answer = io.read ();
describe (answer) 

Working example: http://ideone.com/UJxnpx

Sign up to request clarification or add additional context in comments.

4 Comments

sorry, but, what does _G do?
It is the global scope, where all the global variables are stored. Check the manual for basic functions.
Forget about _G[parent] crap. Use something like this: local data={bob={age=70,hair="black"},dan={age=40,hair="blonde"}; parent = data[parent] or {age=-1,hair=-1}. Access to global variables based on user input - its vulnerability.
Yes, this is more clean solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.