简体   繁体   English

如何使用变量在表Lua中搜索

[英]How to use variable to search in table Lua

I am stuck on this small section of my Lua program. 我被困在Lua程序的这一小部分。 currently I have created a table named GPUtable, the keys are GPU Names and the values are Shader core counts. 当前,我已经创建了一个名为GPUtable的表,键是GPU名称,值是Shader核心计数。 I have used io.write() to create a user input prompt to input a name of a GPU. 我已使用io.write()创建用户输入提示以输入GPU的名称。 I would like to use this input (using choice = io.read()) to search the table and print the shader core count. 我想使用此输入(使用choice = io.read())来搜索表并打印着色器核心数。 for example if the user types HD 7950 I would like print(GPUtable[choice]) to print the shader cores and not nil (error). 例如,如果用户键入HD 7950,则我希望print(GPUtable [choice])打印着色器核心,而不是nil(错误)。 any help is appreciated 任何帮助表示赞赏

If your table keys are indeed the GPU names such as the HD 7950, then indexing it with sqaure brackets will give you what you are looking for. 如果您的表键确实是GPU名称,例如HD 7950,那么用方括号将其索引将为您提供所需的内容。 Without any extra code it is hard to diagnose your issue. 没有任何额外的代码,很难诊断出您的问题。

GPUTable = { ['HD 7950'] = 1792, ['GTX 1080'] = 2560 }
print(GPUTable[io.read()])

Try running this in your emulator, it should work flawlessly. 尝试在模拟器中运行它,它应该可以正常工作。 Your issue could be between receiving the info and indexing. 您的问题可能在接收信息和建立索引之间。 Make sure that the key is a string and is not being changed when it is indexed. 确保键是字符串,并且在索引时不要更改。 Check that your variable names are correct and that you are not trying to use a local variable. 检查变量名是否正确,并且您没有尝试使用局部变量。 It may help to print the 'choice' variable as you are indexing to check for that. 在索引以进行检查时,可能会打印出“ choice”变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM