Lua:函数和用户输入?

我正在尝试在Lua中编写一个简单的程序,根据用户输入返回一些特定值的字符串,但是我编写此脚本时遇到了问题。

例如,如果我编译

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)

我期望如果我输入person1,脚本将返回一个字符串,其内容为:

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

但实际上它会返回一个错误。

问题是,我该怎么做才能解决这个问题?在Lua中正确使用用户输入的方法是什么?

点赞
用户2196426
用户2196426

你需要将 object 传递给函数,而不是名称。或者在全局范围内搜索对象:

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)

工作示例:http://ideone.com/UJxnpx

2016-08-07 06:23:12